[Python] Threading issue causing inconsistent results in Python

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    Threading code with shared global variable counter gives inconsistent results. How to fix thread safety in Python?

    import threading

    counter = 0

    def increment():
    global counter
    for _ in range(1000):
    counter += 1

    def decrement():
    global counter
    for _ in range(1000):
    counter -= 1

    threads = []
    for _ in range(5):
    threads.append(threading.Thread(target=increment))
    threads.append(threading.Thread(target=decrement))

    for thread in threads:
    thread.start()

    for thread in threads:
    thread.join()

    print(f"Counter value: {counter}")

    Continue reading...

Compartilhe esta Página