[英]How to synchronize threads in python?
我在python(2.7)中有兩個線程。 我在程序開始時啟動它們。 當它們執行時,我的程序到達終點並退出,在等待解決之前殺死我的兩個線程。
我想弄清楚如何在退出之前等待兩個線程完成。
def connect_cam(ip, execute_lock):
try:
conn = TelnetConnection.TelnetClient(ip)
execute_lock.acquire()
ExecuteUpdate(conn, ip)
execute_lock.release()
except ValueError:
pass
execute_lock = thread.allocate_lock()
thread.start_new_thread(connect_cam, ( headset_ip, execute_lock ) )
thread.start_new_thread(connect_cam, ( handcam_ip, execute_lock ) )
在.NET中,我會使用像WaitAll()這樣的東西,但我沒有在python中找到相應的東西。 在我的場景中,TelnetClient是一個很長的操作,可能會在超時后導致失敗。
Thread
意味着Python的線程機制的低級原始接口 - 使用threading
代替。 然后,您可以使用threading.join()
來同步線程。
其他線程可以調用線程的join()方法。 這將阻塞調用線程,直到調用其join()方法的線程終止。
Yoo可以這樣做:
import threading
class connect_cam(threading.Thread):
def __init__(self, ip, execute_lock):
threading.Thread.__init__(self)
self.ip = ip
self.execute_lock = execute_lock
def run(self):
try:
conn = TelnetConnection.TelnetClient(self.ip)
self.execute_lock.acquire()
ExecuteUpdate(conn, self.ip)
self.execute_lock.release()
except ValueError:
pass
execute_lock = thread.allocate_lock()
tr1 = connect_cam(headset_ip, execute_lock)
tr2 = connect_cam(handcam_ip, execute_lock)
tr1.start()
tr2.start()
tr1.join()
tr2.join()
使用方法.join(),兩個線程(tr1和tr2)將相互等待。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.