nlib
misc/threading/barrier/barrier.cpp

Sample that uses a barrier that waits for threads.

The BarrierDemo function does the following.

  1. Uses the nn::nlib::threading::Barrier::Init function to set the number of threads to wait for in NUM_THREAD.
  2. Starts NUM_THREAD threads, and runs ThreadFunc.

ThreadFunc waits for other threads every time it displays to the console.

using ::nlib_ns::threading::Barrier;
using ::nlib_ns::threading::Thread;
const int NUM_THREAD = 8;
Thread g_Th[NUM_THREAD];
Barrier g_Barrier;
void ThreadFunc(int n) {
nlib_printf("Thread %d: Step 1\n", n);
g_Barrier.Wait(); // blocks until NUM_THREAD threads comes here
nlib_printf("Thread %d: Step 2\n", n);
g_Barrier.Wait(); // blocks until NUM_THREAD threads comes here
nlib_printf("Thread %d: Step 3\n", n);
g_Barrier.Wait(); // blocks until NUM_THREAD threads comes here
}
bool BarrierDemo() {
nlib_printf("%d threads run, and sync by a Barrier object.\n", NUM_THREAD);
nlib_printf("The Barrier object can sync mutiple times.\n\n");
g_Barrier.Init(NUM_THREAD);
int i;
for (i = 0; i < NUM_THREAD; ++i) {
g_Th[i].Start(ThreadFunc, i);
}
for (i = 0; i < NUM_THREAD; ++i) {
g_Th[i].Join();
}
return true;
}
static bool SampleMain(int, char**) { return BarrierDemo(); }
NLIB_MAINFUNC