[英]Communicate data between threads in python
我是 python 的新手,我對 python 中的線程知之甚少。 這是我的示例代碼。
import threading
from threading import Thread
import time
check = False
def func1():
print ("funn1 started")
while check:
print ("got permission")
def func2():
global check
print ("func2 started")
time.sleep(2)
check = True
time.sleep(2)
check = False
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
我想要的是看到“獲得許可”作為輸出。 但是使用我當前的代碼,它不會發生。 我假設func1
線程在func2
將check
值更改為True
之前關閉。
我怎樣才能保持func1
活着? 我在互聯網上進行了研究,但找不到解決方案。 任何幫助,將不勝感激。 先感謝您!
這里的問題是 func1 在 while 循環中執行檢查,發現它是假的,並終止。 所以第一個線程完成而不打印“獲得許可”。
我不認為這種機制是你正在尋找的。 我會選擇使用這樣的條件,
import threading
from threading import Thread
import time
check = threading.Condition()
def func1():
print ("funn1 started")
check.acquire()
check.wait()
print ("got permission")
print ("funn1 finished")
def func2():
print ("func2 started")
check.acquire()
time.sleep(2)
check.notify()
check.release()
time.sleep(2)
print ("func2 finished")
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
這里的條件變量在內部使用互斥量在線程之間進行通信; 所以一次只有一個線程可以獲取條件變量。 第一個函數獲取條件變量,然后釋放它,但注冊它將等待,直到通過條件變量收到通知。 然后第二個線程可以獲取條件變量,當它完成了它需要做的事情時,它通知等待的線程它可以繼續。
from threading import Thread
import time
check = False
def func1():
print ("funn1 started")
while True:
if check:
print ("got permission")
break
def func2():
global check
print ("func2 started")
time.sleep(2)
check = True
time.sleep(2)
check = False
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
func1
必須是這樣的
def func1():
print("func1 started")
while True:
if check:
print("got permission")
break
else:
time.sleep(0.1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.