Last active
April 27, 2018 21:04
-
-
Save zheltkov/38b1b7788ea607930501b9c6725b34a8 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 <condition_variable> | |
#include <vector> | |
int sum = 0; // sum count | |
constexpr int threadnum = 15; | |
std::mutex print_mutex; | |
std::condition_variable cvs[threadnum]; | |
bool flags[threadnum]; | |
void print_num(int num) { | |
std::mutex m; | |
std::unique_lock<std::mutex> lk(m); | |
for (auto i = 0; i < num+1; i++) { | |
cvs[num].wait(lk, [&] {return flags[num];}); | |
flags[num] = false; | |
{ | |
std::lock_guard<std::mutex> only_print_lock(print_mutex); | |
sum++; | |
std::cout << "Thread: "; | |
std::cout << num + 1; | |
std::cout << " sum count is: "; | |
std::cout << sum << std::endl; | |
} | |
} | |
} | |
void run() { | |
for (int i = 0; i < threadnum; ++i) { | |
flags[i] = true; | |
cvs[i].notify_one(); | |
} | |
} | |
int main() { | |
std::thread threads[threadnum]; | |
for (int id = 0; id < threadnum; id++) | |
threads[id] = std::thread(print_num, id); | |
std::cout << "\nRunning " << threadnum << " in parallel: \n" << std::endl; | |
for (int i = 0; i < 5; ++i) { | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
std::cout << "\n\nemit new event after 3 sec... \n"; | |
std::this_thread::sleep_for(std::chrono::seconds(3)); | |
run(); //new event | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
std::cout << "\n\nemit new event after 5 sec... \n"; | |
std::this_thread::sleep_for(std::chrono::seconds(5)); | |
run(); //new event | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
std::cout << "\n\nemit new event after 7 sec... \n"; | |
std::this_thread::sleep_for(std::chrono::seconds(7)); | |
run(); //new event | |
} | |
for (int id = 0; id < threadnum; id++) | |
threads[id].join(); | |
std::cout << "\nExample complete.\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment