(多线程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,2):
        print(i)
        c.notify()
        c.wait()
    c.release()


t1 = Thread(target=thread_1)
t2 = Thread(target=thread_2)

t1.start()
t2.start()
okyi1 回答:(多线程Python)使用两个线程来交替打印1到10个数字

让线程彼此同步移动很少有用。如果确实需要它们,则可以使用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,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,event_2))

t1.start()
t2.start()

在避免死锁方面,已经有很多关于该主题的文章。在您的特定代码示例中,t1将在t2之前启动,并延伸到c.wait()t2将会启动并到达c.aquire()。两者都将无限期地坐在那儿。避免死锁意味着避免两个线程都等待另一个线程的情况。

本文链接:https://www.f2er.com/3126666.html

大家都在问