nlib
misc/threading/criticalsection/criticalsection.cpp

Critical section sample. This sample increments one counter between multiple threads. The difference between an exclusionary control updating the counter and updating the counter without exclusion is described below.

/*--------------------------------------------------------------------------------*
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