CppCommon  1.0.4.1
C++ Common Library
threads_spin_barrier.cpp

Spin barrier synchronization primitive example

#include "threads/thread.h"
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char** argv)
{
int concurrency = 8;
CppCommon::SpinBarrier 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;
}
Spin barrier synchronization primitive.
Definition: spin_barrier.h:31
bool Wait() noexcept
Wait at the barrier until all other threads reach this barrier.
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
Spin barrier synchronization primitive definition.
Thread definition.