使用信号量的内置函数可能会更好。要等待使用 pthreads 库,您将使用该pend()
函数,并且要使信号量可用,您将使用该post()
函数。
pend
将等到 的值s
大于 0。然后它会自动递减 的值,s
然后继续前进。当然,具体如何实现取决于库。它可能看起来像这样:
sem_wait(){
// Make a kernel function call to guarantee that the following code is atomic
enter_critical_section();
// Test the semaphore value. If it is positive, let the code continue.
int sem_val = s.value;
s.value--;
if (sem_val > 0) {
exit_critical_section();
return;
}
else {
// At this point we know the semaphore value is negative, so it's not available. We'd want to block the caller and make a context switch to a different thread or task.
... // Put the current thread on list of blocked threads
... // Make a context switch to a ready thread.
}
// When the semaphore is made available with a sem_post() function call somewhere else, there will eventually be a context switch back to this (blocked) thread. Simply exit the critical section, return back to the calling function, and let the program execute normally.
exit_critical_section();
}
这段代码实际上是基于我为一个类实现的 RTOS。每个实现看起来都非常不同,还有很多我没有在这里展示,但它应该让你对它如何工作有一个基本的了解。
最后,您在假设的案例中提到有 2 个单独的进程共享一个信号量。这是可能的,您只需确保进行正确的函数调用以使信号量在进程之间可共享。