如何在python中同步线程? [英] How to synchronize threads in python?

查看:93
本文介绍了如何在python中同步线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python(2.7)中有两个线程. 我在程序开始时启动它们.当它们执行时,我的程序到达末尾并退出,在等待解决方案之前杀死了我的两个线程.

I have two threads in python (2.7). I start them at the beginning of my program. While they execute, my program reaches the end and exits, killing both of my threads before waiting for resolution.

我试图弄清楚如何在退出之前等待两个线程完成.

I'm trying to figure out how to wait for both threads to finish before exiting.

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是一个很长的操作,可能会导致超时后失败.

In .NET I would use something like WaitAll() but I haven't found the equivalent in python. In my scenario, TelnetClient is a long operation which may result in a failure after a timeout.

推荐答案

Thread是作为Python线程机制的较低级原始接口-使用

Thread is meant as a lower level primitive interface to Python's threading machinery - use threading instead. Then, you can use threading.join() to synchronize threads.

其他线程可以调用线程的join()方法.这阻止了 调用线程,直到调用了join()方法的线程为止 终止.

Other threads can call a thread’s join() method. This blocks the calling thread until the thread whose join() method is called is terminated.

这篇关于如何在python中同步线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆