Threads tests WIP

This commit is contained in:
Ben Jackson 2020-11-16 22:21:13 +00:00
commit e2ca9b5318
5 changed files with 109 additions and 1 deletions

View file

@ -2,3 +2,4 @@ simple
variables
struct
printer
threads

View file

@ -2,6 +2,7 @@ def Settings( **kwargs ):
return {
'flags': [
'-x', 'c++',
'-std=c++17',
'-Wextra', '-Werror', '-Wall'
]
}

View file

@ -2,7 +2,7 @@ CXXFLAGS=-g -O0 -std=c++17
.PHONY: all
TARGETS=simple variables struct printer
TARGETS=simple variables struct printer threads
all: $(TARGETS)

57
tests/testdata/cpp/simple/threads.cpp vendored Normal file
View file

@ -0,0 +1,57 @@
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <string_view>
#include <system_error>
#include <thread>
#include <vector>
#include <charconv>
#include <random>
int main( int argc, char ** argv )
{
int numThreads = {};
if ( argc < 2 )
{
numThreads = 5;
}
else
{
std::string_view numThreadArg( argv[ 1 ] );
if ( auto [ p, ec ] = std::from_chars( numThreadArg.begin(),
numThreadArg.end(),
numThreads );
ec != std::errc() )
{
std::cerr << "Usage " << argv[ 0 ] << " <number of threads>\n";
return 2;
}
}
std::cout << "Creating " << numThreads << " threads" << '\n';
std::vector<std::thread> threads{};
threads.reserve( numThreads );
auto eng = std::default_random_engine() ;
auto dist = std::uniform_int_distribution<int>( 250, 1000 );
for ( int i = 0; i < numThreads; ++i )
{
using namespace std::chrono_literals;
threads.emplace_back( [&,tnum=i]() {
std::cout << "Started thread " << tnum << '\n';
std::this_thread::sleep_for(
5s + std::chrono::milliseconds( dist( eng ) ) );
std::cout << "Completed thread " << tnum << '\n';
});
}
for ( int i = 0; i < numThreads; ++i )
{
threads[ i ].join();
}
return 0;
}