python - (多线程 Python)交替打印 1 到 10 个数字,使用两个线程
问题描述
请帮助我解决以下死锁情况,同时使用两个线程交替打印 1 到 10 个数字。
请告诉我在多线程 python 中避免死锁情况的最佳实践。
from threading import *
c = Condition()
def thread_1():
c.acquire()
for i in range(1, 11, 2):
print(i)
c.notify()
c.wait()
c.release()
c.notify()
def thread_2():
c.acquire()
c.wait()
for i in range(2, 11, 2):
print(i)
c.notify()
c.wait()
c.release()
t1 = Thread(target=thread_1)
t2 = Thread(target=thread_2)
t1.start()
t2.start()
解决方案
让线程彼此同步移动很少有用。如果你真的需要它们,你可以使用两个独立的事件,正如 Prudhvi 所暗示的那样。例如:
from threading import Thread, Event
event_1 = Event()
event_2 = Event()
def func_1(ev1, ev2):
for i in range(1, 11, 2):
ev2.wait() # wait for the second thread to hand over
ev2.clear() # clear the flag
print('1')
ev1.set() # wake the second thread
def func_2(ev1, ev2):
for i in range(2, 11, 2):
ev2.set() # wake the first thread
ev1.wait() # wait for the first thread to hand over
ev1.clear() # clear the flag
print('2')
t1 = Thread(target=func_1, args=(event_1, event_2))
t2 = Thread(target=func_2, args=(event_1, event_2))
t1.start()
t2.start()
在避免死锁方面,已经有很多关于这个主题的文章。在您的特定代码示例中,t1
将在之前启动t2
并达到c.wait()
. t2
将开火并达到c.aquire()
. 两者都将无限期地坐在那里。避免死锁意味着避免两个线程都等待另一个线程的情况。
推荐阅读
- sql - 无损连接分解属性 - BCNF 分解只有一个无损分解
- python - 如果列包含 Pandas 中的字符,则更改列类型
- cypress - 当 cypress 中的 DOM 中不存在元素时显示错误消息
- web-crawler - 提交的 URL 被 robots.txt 阻止
- vbscript - 经典的 asp 发布登录表单不再起作用
- laravel - 在 Laravel 5.7 中使用 Guzzle 6 在 Sage API 3.1 上工作时缺少请求正文
- jquery - Ajax 表单偶尔会将数据添加到 URL 而不是 POST 然后重定向
- matlab - 如何签署已编译的 matlab 程序的已安装可执行文件?
- c# - 是否有任何预定义的异常类型用作异常列表的容器?
- java - JLabel鼠标事件一键生效两次