nlib
nn::nlib::threading::Barrier Class Referencefinal

Synchronizes an arbitrary number of threads. More...

#include "nn/nlib/threading/Barrier.h"

Public Member Functions

errno_t Init (unsigned int count) noexcept
 Initializes a barrier. More...
 
errno_t Wait () noexcept
 Waits for a thread. More...
 

Detailed Description

Synchronizes an arbitrary number of threads.

Description
Set the number of threads (N) to be synchronized in the Init function. Calling the Wait function stops that thread when the number of threads reached is less than N. All threads are awakened and execution is resumed when the number of ready threads reach N. When this occurs, the counter is reset and the thread halts when it reaches the Wait function.
Sample code is provided below.
const int kNumThread = 4;
std::thread th_list[kNumThread];
nlib_ns::threading::Barrier barrier;
errno_t e = barrier.Init(kNumThread);
SUCCEED_IF(e == 0);
for (auto& th : th_list) {
th = std::thread([](void* p) {
nlib_barrier* pbarrier = reinterpret_cast<nlib_barrier*>(p);
nlib_printf("Thread %d Step1\n", GetMyThreadId());
nlib_barrier_wait(pbarrier); // blocks until kNumThread threads comes here
nlib_printf("Thread %d Step2\n", GetMyThreadId());
nlib_barrier_wait(pbarrier); // blocks until kNumThread threads comes here
}, &barrier);
}
for (auto& th : th_list) {
th.join();
}
/*
Output:
Thread 2388 Step1
Thread 15328 Step1
Thread 8488 Step1
Thread 16144 Step1
Thread 16144 Step2
Thread 15328 Step2
Thread 8488 Step2
Thread 2388 Step2
*/

Definition at line 33 of file Barrier.h.

Member Function Documentation

◆ Init()

nn::nlib::threading::Barrier::Init ( unsigned int  count)
inlinenoexcept

Initializes a barrier.

Parameters
[in]countNumber of threads to wait for.
Return values
0No error occurred.
EINVALIndicates that count is 0.
ENOMEMIndicates that there are not enough system resources.

Definition at line 43 of file Barrier.h.

◆ Wait()

nn::nlib::threading::Barrier::Wait ( )
inlinenoexcept

Waits for a thread.

Return values
0No error occurred.
EBADFIndicates that the Init function has not been called.
ENOMEMIndicates that there are not enough system resources.

Definition at line 51 of file Barrier.h.


The documentation for this class was generated from the following files: