CppCommon  1.0.4.1
C++ Common Library
threads_barrier.cpp

Barrier synchronization primitive example

#include "threads/thread.h"
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char** argv)
{
int concurrency = 8;
CppCommon::Barrier barrier(concurrency);
// Start some threads
std::vector<std::thread> threads;
for (int thread = 0; thread < concurrency; ++thread)
{
threads.emplace_back([&barrier, thread]()
{
std::cout << "Thread " << thread << " initialized!" << std::endl;
// Sleep for a while...
std::cout << "Thread " << thread << " before barrier!" << std::endl;
// Wait for all other threads at the barrier
bool last = barrier.Wait();
std::cout << "Thread " << thread << " after barrier!" << (last ? " Last one!" : "") << std::endl;
});
}
// Wait for all threads
for (auto& thread : threads)
thread.join();
return 0;
}
Barrier synchronization primitive definition.
Barrier synchronization primitive.
Definition: barrier.h:28
bool Wait()
Wait at the barrier until all other threads reach this barrier.
Definition: barrier.cpp:141
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
Thread definition.