#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char** argv)
{
std::string help = "Please enter '+' to notify one waiting thread, enter '*' to notify all waiting threads of the condition variable...";
std::cout << help << std::endl;
int concurrency = 8;
std::atomic<bool> finish(false);
std::vector<std::thread> threads;
for (int thread = 0; thread < concurrency; ++thread)
{
threads.emplace_back([&finish, thread]()
{
std::cout << "Thread " << thread << " initialized!" << std::endl;
std::cout << "Thread " << thread << " waiting for the notification!" << std::endl;
while (!finish)
{
std::cout << "Thread " << thread << " notified!" << std::endl;
}
std::cout << "Thread " << thread << " finished!" << std::endl;
});
}
std::string line;
while (!finish && getline(std::cin, line))
{
if (line == "+")
{
std::cout << "Notify one thread!" << std::endl;
}
else if (line == "*")
{
finish = true;
std::cout << "Notify all threads!" << std::endl;
}
else
std::cout << help << std::endl;
}
for (auto& thread : threads)
thread.join();
return 0;
}
Named condition variable synchronization primitive.
void NotifyOne()
Notify one of waiting thread about event occurred.
void NotifyAll()
Notify all waiting threads about event occurred.
void Wait()
Wait until condition variable is notified.
static void SleepFor(const Timespan ×pan) noexcept
Sleep the current thread for the given timespan.
int64_t milliseconds() const noexcept
Get total milliseconds of the current timespan.
Named condition variable synchronization primitive definition.