CppCommon  1.0.4.1
C++ Common Library
threads_latch_single.cpp

Latch synchronization primitive example for single thread 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(1);
// Start some threads
std::vector<std::thread> threads;
for (int thread = 0; thread < concurrency; ++thread)
{
threads.emplace_back([&latch, thread]()
{
std::cout << "Thread " << thread << " waiting for the latch..." << std::endl;
// Wait for the latch
latch.Wait();
std::cout << "Thread " << thread << " continue!" << std::endl;
// Sleep for a while...
});
}
// Perform some initialization
std::cout << "Main thread initialized!" << std::endl;
// Threads can now start processing
latch.CountDown();
// 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.