typestar

Locks in Python

Guarding shared state so threads don't corrupt it.

import threading

total = 0
lock = threading.Lock()


def add_many(times):
    global total
    for _ in range(times):
        with lock:
            total += 1


threads = [threading.Thread(target=add_many, args=(10_000,))
           for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()

How it works

  1. Four threads all increment the same total.
  2. with lock: makes each increment atomic.
  3. join waits for every thread to finish.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
269
Tokens
81
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 46 seconds.

Type this snippet

Step 2 of 4 in Threads & processes, step 29 of 53 in Pythonic Python.

← Previous Next →