Sobes.tech
Junior — Middle

What methods are used to manage and coordinate threads in Python?

sobes.tech AI

Answer from AI

In Python, the following methods and tools from the threading module are used for thread management and coordination:

  • Creating and starting threads:

    import threading
    
    def worker():
        print("Thread is running")
    
    t = threading.Thread(target=worker)
    t.start()
    t.join()  # Wait for the thread to finish
    
  • Thread synchronization:

    • Lock — a simple mutex to prevent simultaneous access to a resource.
    • RLock — a recursive lock allowing a thread to acquire it multiple times.
    • Event — to notify threads about an event.
    • Condition — for more complex synchronization with waiting and notification.
    • Semaphore — limits the number of threads executing a certain section of code simultaneously.
  • Example of using Lock:

    lock = threading.Lock()
    
    def safe_increment(counter):
        with lock:
            counter[0] += 1
    
  • Coordination using Event:

    event = threading.Event()
    
    def wait_for_event():
        event.wait()  # Wait for the signal
        print("Event occurred")
    
    def trigger_event():
        event.set()  # Send the signal
    

These methods enable the creation of multithreaded applications with access control to shared resources and thread coordination.