クリティカルセクションのサンプルです。 複数のスレッドで同一のカウンタをインクリメントしていくサンプルです。 排他制御をしてカウンタを更新する場合と排他制御をせずにカウンタを更新する場合の動作の違いが説明されています。
using ::nlib_ns::threading::CriticalSection;
int g_counter;
CriticalSection g_lock;
const int kNumThread = 10;
static void IncrementWithoutCriticalSection(void*) {
int tmp = g_counter;
++tmp;
g_counter = tmp;
}
static void IncrementWithCriticalSection(void*) {
g_lock.lock();
IncrementWithoutCriticalSection(NULL);
g_lock.unlock();
}
static bool SampleMain(int, char**) {
nlib_printf(
"g_counter is to be incremented by %d threads\n", kNumThread);
int i;
g_counter = 0;
for (i = 0; i < kNumThread; ++i) {
if (e != 0) {
}
}
for (i = 0; i < kNumThread; ++i) {
}
nlib_printf(
"IncrementWithCriticalSection: g_counter=%d\n", g_counter);
g_counter = 0;
for (i = 0; i < kNumThread; ++i) {
if (e != 0) {
}
}
for (i = 0; i < kNumThread; ++i) {
}
nlib_printf(
"IncrementWithoutCriticalSection: g_counter=%d\n", g_counter);
return true;
}
NLIB_MAINFUNC