#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
std::condition_variable gConditionVariable;
bool gEventIsTriggered = false;
std::mutex gMutex;
struct FunctionClass
{
void operator()()
{
std::cout << "ThreadWaiting:";
std::unique_lock<std::mutex> lock(gMutex);
gConditionVariable.wait(lock, []{return gEventIsTriggered;});
std::cout << "ThreadExiting:";
}
};
int main()
{
std::thread t1{FunctionClass()};
std::thread t2{FunctionClass()};
std::cout << "MainRunning:";
gEventIsTriggered = true;
gConditionVariable.notify_one();
gEventIsTriggered = true;
gConditionVariable.notify_one();
t1.join();
t2.join();
std::cout << std::endl;
return 0;
}
// Output: ThreadWaiting:ThreadWaiting:MainRunning:ThreadExiting:ThreadExiting:
Reference: https://isocpp.org/wiki/faq/cpp11-library-concurrency#std-condition
Monday, September 11, 2017
C++11: Condition Variables
C++11 added Condition Variables. Here is an example:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment