import threading x = 0 lock = threading.Lock() def incr(): global x, lock for i in range(100): with lock: xx = x xx += 1 with lock: x = xx threads = [threading.Thread(target=incr) for _ in range(20)] for t in threads: t.start() for t in threads: t.join() print(x)