使用信號量的內置函數可能會更好。要等待使用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