开发者

Semaphores for process synchronization

I have 开发者_Python百科never understood semaphores well enough. Every time, I venture to understand them, something pops up, which I don't understand.

Here is my question at this moment:

I read in "Operating System Concepts" that: "*A semaphore S is an integer variable that, apart from initialization, is accessed only through two standard atomic operations: wait() and signal()."*

What does atomic mean here? Does it mean that this operation will be executed at one go?

But then the book goes on to give one sample implementation of wait():

wait(S) {
while S <= 0
; // no-op
S--;
}

With a while loop in it (which depends on other process), how can this ever run at one go (i.e. without any other process executing to signal, which will break the while loop)

Please explain,


The example code for wait is just illustrative, it's unlikely it would be implemented in this way. Most operating systems would suspend the tread trying to acquire the semaphore if the counter is not greater than zero.

However, technically the example can be made to work. If S was flagged as volatile then a change by any other process or thread would be seen by wait(). wait() would spin in a tight loop until the condition was satisfied and would chew up the CPU, but it would work. Note that this CPU chewing is why a OS will suspend the calling thread is the condition cannot be satisfied. You'd need to do the test and decrement atomically, and this is typically accomplished by using an OS atomic function, such as InterlockedCompareExchange on Windows.


Does it mean that this operation will be executed at one go?

Essentially, yes.

The example is not an actual implementation, (I hope!), just a C-style representation of the functionality. Actual implementations are OS/CPU specific since kernel/hardware support is required to eliminate busy-waiting and to ensure correct operation on multicore processors.

Rgds, Martin

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜