我有一个类似的问题,我认为会有相同的答案,即“如何使用互斥锁实现计数信号量”。
请注意,二进制信号量可以被认为是互斥体。事实上,在不提供互斥锁的系统上,可以使用二进制信号量来提供互斥。
Mutex counting_mutex; // used for accessing the shared variable count
Integer count = n; // number of resource instances
Mutex mutex; // the counting semaphore as mutex/binary semaphore
List waiting_list = []; // list of waiting processes
/* ... */
// Entry Section
acquire(counting_mutex);
count--;
release(counting_mutex);
if (count < 0)
add this process to waiting_list and have it sleep()
acquire(mutex);
/* ... Critical Section ... */
release(mutex);
// Exit Section
acquire(counting_mutex);
count++;
release(counting_mutex);
if (count <= 0)
pull a process from waiting_list and call wakeup()