How to synchronize threads in python?

孤街醉人 提交于 2019-12-06 06:21:34

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.

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

Yoo can do something like that:

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()

With the method .join(), the two threads (tr1 and tr2) will wait for each other.

First, you ought to be using the threading module, not the thread module. Next, have your main thread join() the other threads.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!