Skip to content

Instantly share code, notes, and snippets.

@Mooophy
Last active August 29, 2015 14:09
Show Gist options
  • Save Mooophy/49c0c7a401ff0f27a057 to your computer and use it in GitHub Desktop.
Save Mooophy/49c0c7a401ff0f27a057 to your computer and use it in GitHub Desktop.
#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