Last active
August 29, 2015 14:09
-
-
Save Mooophy/49c0c7a401ff0f27a057 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <thread> | |
#include <mutex> | |
#include <vector> | |
struct ThreadTest | |
{ | |
ThreadTest(): | |
threads_vector{10} | |
{ | |
for(unsigned idx=0; idx!=threads_vector.size(); ++idx) | |
{ | |
threads_vector[idx] = std::thread{ [=]{print(idx);} }; | |
} | |
} | |
~ThreadTest() | |
{ | |
wait_for_all_to_join(); | |
} | |
void print(unsigned task_id) | |
{ | |
std::lock_guard<std::mutex> lock{mutex}; | |
//! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | |
//! grantee that only one thread is using ostream | |
std::cout << "thread : " << task_id << std::endl; | |
} | |
static std::mutex mutex; | |
std::vector<std::thread> threads_vector; | |
void wait_for_all_to_join() | |
{ | |
for(auto& t : threads_vector) t.join(); | |
} | |
}; | |
std::mutex ThreadTest::mutex; | |
int main() | |
{ | |
ThreadTest test; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment