CppCommon  1.0.4.1
C++ Common Library
threads_latch_multi.cpp

Latch synchronization primitive example for multiple threads waiting

#include "threads/latch.h"
#include "threads/thread.h"
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char** argv)
{
int concurrency = 8;
CppCommon::Latch latch(concurrency);
// Start some threads
std::vector<std::thread> threads;
for (int thread = 0; thread < concurrency; ++thread)
{
threads.emplace_back([&latch, thread]()
{
std::cout << "Thread " << thread << " initialized!" << std::endl;
// Sleep for a while...
// Count down the latch
latch.CountDown();
std::cout << "Thread " << thread << " latch count down!" << std::endl;
});
}
std::cout << "Main thread is waiting for the latch..." << std::endl;
// Wait until work is done
latch.Wait();
std::cout << "Main thread continue!" << std::endl;
// Wait for all threads
for (auto& thread : threads)
thread.join();
return 0;
}
Latch synchronization primitive.
Definition: latch.h:29
void CountDown() noexcept
Countdown the latch.
Definition: latch.cpp:42
void Wait() noexcept
Wait for the latch.
Definition: latch.cpp:65
static void SleepFor(const Timespan &timespan) noexcept
Sleep the current thread for the given timespan.
Definition: thread.cpp:83
int64_t milliseconds() const noexcept
Get total milliseconds of the current timespan.
Definition: timespan.h:141
Latch synchronization primitive definition.
Thread definition.