Last active
May 23, 2018 21:06
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 <future> | |
#include <thread> | |
#include <string> | |
#include <condition_variable> | |
#include <vector> | |
std::mutex m1; | |
std::mutex cout_mutex; | |
std::condition_variable wait_till_run; | |
bool go = false; | |
void hundredMeterRace(const std::string& name) | |
{ | |
{ | |
std::unique_lock<std::mutex> lg(m1); | |
wait_till_run.wait(lg, []() | |
{ | |
return go; | |
}); | |
} | |
std::lock_guard<std::mutex> cm(cout_mutex); | |
std::cout << name << " starts running\n"; | |
} | |
int main() | |
{ | |
std::vector<std::thread> vcTh; | |
std::vector<std::string> names = { "Nash", "Sam", "Bolt" }; | |
for (const auto& name : names) | |
{ | |
vcTh.emplace_back(hundredMeterRace, std::cref(name)); | |
} | |
{ | |
std::lock_guard<std::mutex> cm(cout_mutex); | |
std::cout << "Ready .... Set ... Go\n"; | |
} | |
go = true; | |
wait_till_run.notify_all(); | |
for (auto& th : vcTh) | |
{ | |
th.join(); | |
} | |
} | |
/*Output | |
Ready .... Set ... Go | |
Sam starts running | |
Nash starts running | |
Bolt starts running | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment