Created
November 14, 2014 23:47
-
-
Save Mooophy/dcf787fd4e2f500fbb38 to your computer and use it in GitHub Desktop.
using std::thread std::mutex std::lock_guard in the same class
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> | |
struct ThreadTest | |
{ | |
ThreadTest(): | |
t1{[this]{ print(1);} }, | |
t2{[this]{ print(2);} } | |
{} | |
~ThreadTest() | |
{ | |
wait_for_all_to_join(); | |
} | |
void print(unsigned task_id) | |
{ | |
std::lock_guard<std::mutex> lock{mutex}; | |
std::cout << "thread : " << task_id << std::endl; | |
} | |
static std::mutex mutex; | |
std::thread t1; | |
std::thread t2; | |
void wait_for_all_to_join() | |
{ | |
t1.join(); | |
t2.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