关于条件变量
来源:8-3 实现线程安全的队列Queue

Umud
2020-07-13
为什么调用self.condition.notify之前,需要调用self.condition.acquire()?
为什么不直接调用self.condition.notify?
2回答
-
这是Python条件变量的正确使用方法,需要先获得锁再notify然后再release,否则有可能会引起死锁。
因为条件变量在某种程度上是和锁绑定在一起的,当条件变量在wait的时候,线程会释放锁,但是notify或者notifyAll方法,不会释放锁,因此当notify之后,正在等待(wait)的线程并不会马上被唤醒,而是要等待锁释放,才能继续往下走,所以在notify的前后需要有acquire和release。
引用下Python标准库的官方说明:Note: the notify() and notifyAll() methods don't release the lock; this means that the thread or threads awakened will not return from their wait() call immediately, but only when the thread that called notify() or notifyAll() finally relinquishes ownership of the lock.
希望对你有所帮助。
10 -
Umud
提问者
2020-07-14
我是这样思考的:self.lock.acquire 执行获取锁就意味着当前线程获取CPU资源,把item添加到queue里面,然后通知其他线程可以自己的item添加queue里面,然后释放锁把CPU资源让给其他线程。
为什么你写的代码两次获取锁,然后两次释放锁?
这样(上面的图片)写可以吗?
00
相似问题
回答 2
回答 1