nlib
misc/threading/criticalsection/criticalsection.cpp

クリティカルセクションのサンプルです。 複数のスレッドで同一のカウンタをインクリメントしていくサンプルです。 排他制御をしてカウンタを更新する場合と排他制御をせずにカウンタを更新する場合の動作の違いが説明されています。

/*---------------------------------------------------------------------------*
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::CriticalSection;
using ::nlib_ns::threading::Thread;
int g_Counter;
CriticalSection g_Lock;
const int NUM_THREAD = 10;
Thread g_Th[NUM_THREAD];
static void IncrementWithoutCriticalSection() {
int tmp = g_Counter;
++tmp;
g_Counter = tmp;
}
static void IncrementWithCriticalSection() {
g_Lock.lock();
IncrementWithoutCriticalSection();
g_Lock.unlock();
}
static bool SampleMain(int, char**) {
nlib_printf("g_Counter is to be incremented by %d threads\n", NUM_THREAD);
int i;
// increments g_Counter without lock
g_Counter = 0;
for (i = 0; i < NUM_THREAD; ++i) {
g_Th[i].Start(IncrementWithCriticalSection);
}
for (i = 0; i < NUM_THREAD; ++i) {
g_Th[i].Join();
}
nlib_printf("IncrementWithCriticalSection: g_Counter=%d\n", g_Counter);
// increments g_Counter without locking
g_Counter = 0;
for (i = 0; i < NUM_THREAD; ++i) {
g_Th[i].Start(IncrementWithoutCriticalSection);
}
for (i = 0; i < NUM_THREAD; ++i) {
g_Th[i].Join();
}
nlib_printf("IncrementWithoutCriticalSection: g_Counter=%d\n", g_Counter);
return true;
}
NLIB_MAINFUNC