On this page
  1. threading.Lock
  2. Import
  3. Signature & Overview
  4. Methods & Attributes
  5. Usage
  6. Gotchas
  7. REPL Inspect

threading.Lock

Prev: threading.local | Up: threading | Next: threading.main_thread
Rel: threading.active_count, threading.Barrier, threading.BoundedSemaphore, threading.BrokenBarrierError
Ref: docs.python.org — threading.Lock
Tags: #public #python3 #stdlib #threading


Import

import threading
from threading import Lock

Signature & Overview

threading.Lock()

A lock object is a synchronization primitive. To create a lock, call threading.Lock(). Methods are: acquire() -- lock the lock, possibly blocking until it can be obtained

Methods & Attributes

Usage

import threading

lock = threading.Lock()
counter = 0

def inc() -> None:
    global counter
    for _ in range(1000):
        with lock:
            counter += 1

threads = [threading.Thread(target=inc) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
assert counter == 4000

Gotchas

REPL Inspect

from threading import Lock
help(Lock)

Linked from

Related notes