Race Condition Doesn't happen

Viewed 33

I have written a bit of code to see the race condition, But it Doesn't happen.

class SharedContent:
    def __init__(self, initia_value = 0) -> None:
        self.initial_value = initia_value

    def incerease(self ,delta = 1):
        sleep(1)
        self.initial_value += delta

content = SharedContent(0)
threads: list[Thread] = []
for i in range(250):
    t = Thread(target=content.incerease)
    t.start()
    threads.append(t)

#wait until all threads have finished their job
while True:
    n = 0
    for t in threads:
        if t.is_alive():
            sleep(0.2)
            continue
        n += 1
    if n == len(threads):
        break
print(content.initial_value)

The output is 250 which implies no race condition has happened! Why is that?

I even tried this with random sleep time but the output was the same.

1 Answers

I changed your program. This version prints a different number every time I run it.

#!/usr/bin/env python3

from threading import Thread

class SharedContent:
    def __init__(self, initia_value = 0) -> None:
        self.initial_value = initia_value

    def incerease(self ,delta = 1):
        for i in range(0, 1000000):
            self.initial_value += delta

content = SharedContent(0)
threads = []
for i in range(2):
    t = Thread(target=content.incerease)
    t.start()
    threads.append(t)

#wait until all threads have finished their job
for t in threads:
    t.join()
print(content.initial_value)

What I changed:

  • Only two threads instead of 250.
  • Got rid of sleep() calls.
  • Each thread increments the variable one million times instead of just one time.
  • Main program uses join() to wait for the threads to finish.
Related