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 kNumThread.
  2. Starts kNumThread threads, and runs ThreadFunc.

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

/*--------------------------------------------------------------------------------*
Project: CrossRoad
Copyright (C)Nintendo All rights reserved.
These coded instructions, statements, and computer programs contain proprietary
information of Nintendo and/or its licensed developers and are protected by
national and international copyright laws. They may not be disclosed to third
parties or copied or duplicated in any form, in whole or in part, without the
prior written consent of Nintendo.
The content herein is highly confidential and should be handled accordingly.
*--------------------------------------------------------------------------------*/
using ::nlib_ns::threading::Barrier;
using ::nlib_ns::threading::Thread;
const int kNumThread = 8;
Thread g_th[kNumThread];
Barrier g_barrier;
void ThreadFunc(int n) {
nlib_printf("Thread %d: Step 1\n", n);
g_barrier.Wait(); // blocks until kNumThread threads comes here
nlib_printf("Thread %d: Step 2\n", n);
g_barrier.Wait(); // blocks until kNumThread threads comes here
nlib_printf("Thread %d: Step 3\n", n);
g_barrier.Wait(); // blocks until kNumThread threads comes here
}
bool BarrierDemo() {
nlib_printf("%d threads run, and sync by a Barrier object.\n", kNumThread);
nlib_printf("The Barrier object can sync mutiple times.\n\n");
g_barrier.Init(kNumThread);
int i;
for (i = 0; i < kNumThread; ++i) {
g_th[i].Start(ThreadFunc, i);
}
for (i = 0; i < kNumThread; ++i) {
g_th[i].Join();
}
return true;
}
static bool SampleMain(int, char**) { return BarrierDemo(); }
NLIB_MAINFUNC