nlib
misc/threading/barrier/barrier.cpp

スレッドの待ち合わせを行うバリアを利用するサンプルです。

BarrierDemo()関数では以下のことを行なっています。

  1. nn::nlib::threading::Barrier::Init()関数で待ち合わせスレッドの数をNUM_THREAD個に設定します。
  2. スレッドをNUM_THREAD個立ち上げ、ThreadFunc()を実行させます。

ThreadFunc()関数ではコンソールへの表示を行う度に他のスレッドを待ち合わせています。

/*---------------------------------------------------------------------------*
Project: CrossRoad
Copyright (C)2012-2016 Nintendo. All rights reserved.
These coded instructions, statements, and computer programs contain
proprietary information of Nintendo of America Inc. and/or Nintendo
Company Ltd., and are protected by Federal copyright law. 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.
*---------------------------------------------------------------------------*/
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