首页 > 解决方案 > (多线程 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()

标签: pythonmultithreadingdeadlock

解决方案


让线程彼此同步移动很少有用。如果你真的需要它们,你可以使用两个独立的事件,正如 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(). 两者都将无限期地坐在那里。避免死锁意味着避免两个线程都等待另一个线程的情况。


推荐阅读