pytho 解锁后通知其他线程
时间: 2023-06-05 07:04:24 浏览: 65
可以使用 Python 中的 threading.Condition 类来进行线程通信和同步。当主线程需要通知其他线程时,调用 Condition 对象的 notify_all() 方法。其他线程可以通过调用 Condition 对象的 wait() 方法来等待主线程的通知。同时,也需要一个共享的锁来保证同步。具体实现可以参考以下代码:
```python
import threading
def worker(condition):
with condition:
print(f"Thread {threading.current_thread().name} is waiting")
condition.wait()
print(f"Thread {threading.current_thread().name} has received a notification")
def main():
condition = threading.Condition()
threads = [
threading.Thread(name=f"Thread {i}", target=worker, args=(condition,))
for i in range(5)
]
for t in threads:
t.start()
with condition:
print("Main thread is doing some work")
condition.notify_all()
for t in threads:
t.join()
if __name__ == "__main__":
main()
```
当主线程执行到 `condition.notify_all()` 时,所有等待的子线程会被唤醒并继续执行。运行结果如下:
```python
Thread Thread 0 is waiting
Thread Thread 1 is waiting
Thread Thread 2 is waiting
Thread Thread 3 is waiting
Thread Thread 4 is waiting
Main thread is doing some work
Thread Thread 0 has received a notification
Thread Thread 1 has received a notification
Thread Thread 2 has received a notification
Thread Thread 3 has received a notification
Thread Thread 4 has received a notification
```