繁体   English   中英

如何在python中同步线程?

[英]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)将相互等待。

首先,您应该使用线程模块,而不是线程模块。 接下来,让你的主线程join()其他线程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM