nlib
misc/threading/criticalsection/criticalsection.cpp

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

/*--------------------------------------------------------------------------------*
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::CriticalSection;
using ::nlib_ns::threading::Thread;
int g_counter;
CriticalSection g_lock;
const int kNumThread = 10;
Thread g_th[kNumThread];
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", kNumThread);
int i;
// increments g_counter without lock
g_counter = 0;
for (i = 0; i < kNumThread; ++i) {
g_th[i].Start(IncrementWithCriticalSection);
}
for (i = 0; i < kNumThread; ++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 < kNumThread; ++i) {
g_th[i].Start(IncrementWithoutCriticalSection);
}
for (i = 0; i < kNumThread; ++i) {
g_th[i].Join();
}
nlib_printf("IncrementWithoutCriticalSection: g_counter=%d\n", g_counter);
return true;
}
NLIB_MAINFUNC