我有 thread1、thread2 和 thread3、全域變數x和三個不同的函式來增加x,
import threading
import time
#check = threading.Condition()
x=1
def add_by1():
global x
x =1
time.sleep(1)
print(x)
def add_by2():
x =2
time.sleep(1)
print(x)
def add_by3():
x =3
time.sleep(1)
print(x)
if __name__==__main__:
threading.Thread(target=add_by1).start()
threading.Thread(target=add_by2).start()
threading.Thread(target=add_by3).start()
# I want the output should print..
"""
2
4
7
8
10
13
14
16
19
and so on ..
"""
我可以使用Condition()嗎?如果可以,如何使用?我可以使用其他執行緒類嗎?如何在這些函式上插入一些代碼?
uj5u.com熱心網友回復:
我想這種方法是可靠的。您可以使用三個物件同步您的執行緒lock- 每個物件一個。
此設定的作業方式是每個執行緒獲取其鎖,并在完成其作業后釋放下一個執行緒的鎖!IOW,add_by1發布thread_lock_two,add_by2發布thread_lock_three,最后add_by3發布thread_lock_one。
最初您需要獲取thread_lock_twoandthread_lock_three的鎖,以便只有第一個執行緒執行其作業。
只要滿足條件(你說的),每個執行緒也x == 20應該再次釋放下一個執行緒的鎖! return
import threading
from time import sleep
x = 1
thread_lock_one = threading.Lock()
thread_lock_two = threading.Lock()
thread_lock_three = threading.Lock()
thread_lock_two.acquire()
thread_lock_three.acquire()
def add_by1():
global x
while True:
thread_lock_one.acquire()
if x >= 20:
thread_lock_two.release()
return
x = 1
print(x)
sleep(0.6)
thread_lock_two.release()
def add_by2():
global x
while True:
thread_lock_two.acquire()
if x >= 20:
thread_lock_three.release()
return
x = 2
print(x)
sleep(0.6)
thread_lock_three.release()
def add_by3():
global x
while True:
thread_lock_three.acquire()
if x >= 20:
thread_lock_one.release()
return
x = 3
print(x)
sleep(0.6)
thread_lock_one.release()
if __name__ == "__main__":
threading.Thread(target=add_by1).start()
threading.Thread(target=add_by2).start()
threading.Thread(target=add_by3).start()
輸出:
2
4
7
8
10
13
14
16
19
20
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/535808.html
上一篇:將執行緒轉換為多行程池
下一篇:讀寫鎖(作者首選)實作
