Created
April 6, 2018 11:39
-
-
Save alpinskiy/d403a8e27bb10ec8e005f354bfee7249 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 <condition_variable> | |
#include <future> | |
#include <iostream> | |
#include <mutex> | |
#include <thread> | |
#include <vector> | |
using namespace std; | |
condition_variable CondVar; | |
mutex Mutex; | |
int SemaphorCount{0}; | |
bool RunFlag{false}, StopFlag{false}; | |
void worker() { | |
for (auto stop_flag{false}; !stop_flag;) { | |
{ | |
unique_lock<mutex> lock{Mutex}; | |
CondVar.wait(lock, [] { return SemaphorCount; }); | |
--SemaphorCount; | |
cout << ">" << this_thread::get_id() << endl; | |
} | |
unique_lock<mutex> lock{Mutex}; | |
++SemaphorCount; | |
stop_flag = StopFlag; | |
cout << "<" << this_thread::get_id() << endl; | |
} | |
} | |
int main() { | |
vector<future<void>> workers; | |
workers.push_back(async(launch::async, []() { worker(); })); | |
workers.push_back(async(launch::async, []() { worker(); })); | |
workers.push_back(async(launch::async, []() { worker(); })); | |
workers.push_back(async(launch::async, []() { worker(); })); | |
cout << "Press any key to run..." << endl; | |
string line; | |
getline(cin, line); | |
{ | |
unique_lock<mutex> lock{Mutex}; | |
SemaphorCount = workers.size() / 2; | |
CondVar.notify_all(); | |
} | |
cout << "Press any key to stop..." << endl; | |
getline(cin, line); | |
{ | |
unique_lock<mutex> lock{Mutex}; | |
StopFlag = true; | |
CondVar.notify_all(); | |
} | |
vector<future<void>>{}.swap(workers); | |
cout << SemaphorCount << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment