用于进程同步的信号量
我对信号量的理解一直不够好。每次当我尝试去理解它们时,就会出现一些我不理解的东西。
这是我现在的问题:
我在“操作系统概念”中读到:”*信号量 S 是一个整数变量,除了初始化之外,只能通过两个标准原子操作来访问: wait( ) 和 signal()。"*
这里的atomic 是什么意思?是说这个操作会一次性执行吗?
但是本书接着给出了 wait() 的一个示例实现:
wait(S) {
while S <= 0
; // no-op
S--;
}
其中有一个 while 循环(这取决于其他进程),它如何能够一次性运行(即没有任何其他进程执行来发出信号,这将导致打破 while 循环)
请解释一下,
I have 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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
wait 的示例代码只是说明性的,不太可能以这种方式实现。如果计数器不大于零,大多数操作系统将暂停尝试获取信号量的进程。
然而,从技术上讲,这个例子是可以工作的。如果 S 被标记为易失性,那么任何其他进程或线程的更改都会被 wait() 看到。 wait() 会在一个紧密的循环中旋转,直到满足条件为止,并且会消耗 CPU,但它会起作用。请注意,这种 CPU 消耗是操作系统在条件无法满足时挂起调用线程的原因。您需要以原子方式进行测试和递减,这通常是通过使用操作系统原子函数(例如 Windows 上的 InterlockedCompareExchange)来完成的。
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.
是说这个操作会一次性执行吗?
本质上是的。
该示例不是实际的实现(我希望如此!),只是功能的 C 风格表示。实际实现是特定于操作系统/CPU 的,因为需要内核/硬件支持来消除忙等待并确保多核处理器上的正确操作。
平均值,
马丁
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