使用信号量的内置函数可能会更好。要等待使用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个独立进程。这是可能的,你只需要做出正确的函数调用来使信号量在进程之间共享。
非零计数和减量的等待通常在操作系统的内核中进行处理,方式是使检查和递减为原子操作。 – rcgldr