[Python] I am trying to cause race condition for demonstration purposes but fail to fail

Discussão em 'Python' iniciado por Stack, Janeiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am actively trying to get race condition and cause problem in calculation for demonstration purposes but i can't achieve such problem simply.

    My tought process was to create a counter variable, reach it from diffrent threads and async functions (i did not tried mp since it pauses process) and increase it by one.

    Running 3 instances of for loops in range x and increasing the counter by 1 in each loop i expected to get value lower then 3x due to race condition.

    I did not use locks, but i still get 3x value each run. Does it due to GIL update? i have tried with python versions 3.10 / 3.11 / 3.13. What should i do to get race condition simple structure

    my code to get race condition

    import threading
    import asyncio

    def multithreading_race_condition():
    counter2 = 0

    def increment():
    nonlocal counter2
    for _ in range(10000):
    counter2 = counter2 + 1

    threads = [threading.Thread(target=increment) for _ in range(3)]

    for t in threads:
    t.start()

    for t in threads:
    t.join()

    print(f"Multithreading Final Counter: {counter2}")

    async def asyncio_race_condition():
    counter3 = 0

    async def increment():
    nonlocal counter3
    for _ in range(10000):
    counter3 = counter3 + 1

    tasks = [asyncio.create_task(increment()) for _ in range(3)]

    await asyncio.gather(*tasks)

    print(f"Asyncio Final Counter: {counter3}")

    def main():
    print("\nMultithreading Example:")
    multithreading_race_condition()

    print("\nAsyncio Example:")
    asyncio.run(asyncio_race_condition())

    if __name__ == "__main__":
    main()


    my output is

    Multithreading Example:
    Multithreading Final Counter: 30000

    Asyncio Example:
    Asyncio Final Counter: 30000

    Continue reading...

Compartilhe esta Página