A semaphore sample. A semaphore is a mechanism to use a limited resource between multiple threads.
Perform the following processes in the main thread.
-
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.
-
Start
kNumThread
threads.
-
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.
-
Waits until a semaphore is acquired in the
nn::nlib::threading::Semaphore::Acquire
function.
-
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.
-
Releases a semaphore in the
nn::nlib::threading::Semaphore::Release
function, incrementing semaphore by 1.
using ::nlib_ns::threading::Semaphore;
const int kNumThread = 10;
Semaphore g_semaphore;
void SemaphoreDemoFunc(void* p) {
int thread_num = static_cast<int>(reinterpret_cast<intptr_t>(p));
nlib_printf(
" Thread %d, Trying wait semaphore\n", thread_num);
g_semaphore.Acquire();
nlib_printf(
" Thread %d, Success get semaphore\n", thread_num);
for (int i = 0; i < 2; ++i) {
nlib_printf(
" Thread %d, doing jobs using limited resource\n", thread_num);
}
nlib_printf(
" Thread %d, Release semaphore\n", thread_num);
g_semaphore.Release(NULL);
}
bool SemaphoreDemo() {
e = g_semaphore.Init(0);
if (e != 0) return false;
intptr_t i;
for (i = 0; i < kNumThread; ++i) {
if (e != 0) return false;
}
e = g_semaphore.Release(2, NULL);
NLIB_ASSERT_NOERR(e);
for (i = 0; i < kNumThread; ++i) {
}
return true;
}
static bool SampleMain(int, char**) { return SemaphoreDemo(); }
NLIB_MAINFUNC