Context manager

Kõik acquire() ja release() kasutavad objektid saavad eelnevalt mainitud kutsed asendada with-võtmesõnaga. Selle eelis on puhtam ja turvalisem kood: erindi tekkel automaatne lukkudest vabastamine.

Toetatud objektid

  1. Lock:

    lock = threading.Lock()
    with lock:
        print("Lock Shop closed - only one thread at the time")
    
  2. RLock:

    rlock = threading.RLock()
    def recursive(n):
        with rlock:
            print(" Inside RLock: ", n)
            if n > 0:
                recursive(n-1)
    recursive(2)
    
  3. Condition:

    # Consume one item
    with cv:
        while not an_item_is_available():
            cv.wait()
        get_an_available_item()
    
    # Produce one item
    with cv:
        make_an_item_available()
        cv.notify()
    
  4. Semaphore:

    sema = threading.Semaphore(2)  # max 2
    def worker(name):
        with sema:
            print(f"{name} inside semaphore")
    threading.Thread(target=worker, args=("A",)).start()
    threading.Thread(target=worker, args=("B",)).start()
    threading.Thread(target=worker, args=("C",)).start()
    
  5. Semaphore:

    bsema = threading.BoundedSemaphore(1)
    with bsema:
        print("BoundedSemaphore shop closed - only one thread at the time")