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.
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;
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);
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