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 are running, my program reaches the end and exits, killing both of my threads before waiting for permission.

I am trying to figure out how to wait for both threads to complete 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 did not find the equivalent in python. In my script, TelnetClient is a long operation that can lead to a crash after a timeout.

+2
python multithreading synchronization locking
source share
3 answers

Thread meant as a primitive lower-level interface for Python Threading machines - use threading instead. Then you can use threading.join() to synchronize threads.

Other threads may call the join threads () method. This blocks the calling thread until a thread is called whose join () method terminates.

+4
source share

Yoo might do something like this:

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

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

+3
source share

First, you should use the threading module, not the thread module. Then add your main join () thread to the other threads.

+2
source share

All Articles