Skip to content

Instantly share code, notes, and snippets.

@avi007i
Last active May 23, 2018 21:06
#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