通过线程打印奇数和偶数之间的同步

时间:2019-01-06 06:59:46

标签: python python-3.x

此代码将输出显示为

0 1 3 2 5 4 7 6 8 9 10 11 12 13 14 15 16 17 18 19 20

无法判断错误。我们希望将输出显示为

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

代码:

from threading import Thread, Lock

from time import sleep

mylock1 = Lock()
#mylock2 = Lock()

def evenprint ( uservalue):#dunder __init__
    for i in range(0,uservalue,2):
        sleep(1)
        mylock1.acquire(True)
        print(i,end=' ')
        mylock1.release()
def oddprint(uservalue):
    for i in range(1,uservalue,2):
        sleep(1)
        mylock1.acquire(True)
        print(i,end=' ')
        mylock1.release()

variable=21
t1= Thread(target=evenprint,args=(variable,))
t2= Thread(target=oddprint,args=(variable,))

t1.start()
t2.start()

0 个答案:

没有答案