Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <thread>
- #include <iostream>
- using namespace std;
- void test_thread(int id)
- {
- int wait = 5 -id;
- std::cout << "echo from thread " << id << " with " << wait << " delay" << std::endl;
- std::this_thread::sleep_for (std::chrono::seconds(wait));
- std::cout << "end from thread " << id << " with " << wait << " delay" << std::endl;
- }
- void start_thread(int concurentThreadsSupported)
- {
- std::cout << "Using " << concurentThreadsSupported << " concurrent threads" << std::endl;
- std::thread * threads = new std::thread[concurentThreadsSupported];
- for (int i = 0; i < concurentThreadsSupported; ++i)
- {
- std::cout << "CREATE " << i << std::endl;
- threads[i] = std::thread(test_thread, i);
- std::cout << "CREATED " << i << std::endl;
- std::this_thread::sleep_for (std::chrono::seconds(1));
- }
- std::this_thread::sleep_for (std::chrono::seconds(concurentThreadsSupported+2));
- std::cout << "echo from thread BASE" << std::endl;
- for (int i = 0; i < concurentThreadsSupported; ++i)
- {
- std::cout << "START " << i << std::endl;
- threads[i].join();
- std::cout << "OK " << i << std::endl;
- }
- std::cout << "end from thread BASE" << std::endl;
- delete [] threads;
- }
- int main()
- {
- unsigned concurentThreadsSupported = std::thread::hardware_concurrency();
- if(concurentThreadsSupported == 0){
- std::cout << "Can't get number of hardware threads" << std::endl;
- concurentThreadsSupported = 1;
- }
- std::cout << "echo from MAIN" << std::endl;
- start_thread(concurentThreadsSupported);
- std::cout << "end from MAIN" << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment