nlib
misc/threading/semaphore/semaphore.cpp

A semaphore sample. A semaphore is a mechanism to use a limited resource between multiple threads.

Perform the following processes in the main thread.

  1. Use nn::nlib::threading::Semaphore::Init to set the maximum value to 2 and the initial semaphore count to 0, where the semaphore is unobtainable.
  2. Start NUM_THREAD threads.
  3. Releasing the semaphore and setting the semaphore count to 2 allows a maximum of two threads to get a semaphore.

In other threads, perform the following processes with the SemaphoreDemoFunc() function.

  1. Waits until a semaphore is acquired in the nn::nlib::threading::Semaphore::Acquire function.
  2. Sleeps twice for one millisecond each time when a semaphore is acquired (and decrements the semaphore count by 1). Up to two threads can run this process.
  3. Releases a semaphore in the nn::nlib::threading::Semaphore::Release function, incrementing semaphore by 1.
using ::nlib_ns::threading::Semaphore;
using ::nlib_ns::threading::Thread;
const int NUM_THREAD = 10;
Thread g_Th[NUM_THREAD];
Semaphore g_Semaphore;
void SemaphoreDemoFunc(int threadNum) {
nlib_printf(" Thread %d, Trying wait semaphore\n", threadNum);
g_Semaphore.Acquire();
nlib_printf(" Thread %d, Success get semaphore\n", threadNum);
for (int i = 0; i < 2; ++i) {
nlib_printf(" Thread %d, doing jobs using limited resource\n", threadNum);
}
nlib_printf(" Thread %d, Release semaphore\n", threadNum);
g_Semaphore.Release(NULL);
}
bool SemaphoreDemo() {
nlib_printf("-- Semaphore Demo --\n");
// initializes Semaphore
e = g_Semaphore.Init(0);
if (e != 0) return false;
int i;
for (i = 0; i < NUM_THREAD; ++i) {
e = g_Th[i].Start(SemaphoreDemoFunc, i);
NLIB_ASSERT_NOERR(e);
}
// NUM_THREAD threads share 2 resources
nlib_printf("Main Thread: Release semaphores\n");
e = g_Semaphore.Release(2, NULL);
NLIB_ASSERT_NOERR(e);
for (i = 0; i < NUM_THREAD; ++i) {
e = g_Th[i].Join();
NLIB_ASSERT_NOERR(e);
}
return true;
}
static bool SampleMain(int, char**) { return SemaphoreDemo(); }
NLIB_MAINFUNC