Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synchronize threads in python?

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

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.

like image 353
Eric Avatar asked Jun 23 '26 10:06

Eric


2 Answers

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.

like image 153
Aphex Avatar answered Jun 25 '26 00:06

Aphex


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.

like image 35
Srtab Avatar answered Jun 25 '26 00:06

Srtab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!