Understanding a race condition

The 9.01_race_condition.py code demonstrates a race condition. The program is as follows:

import threading

class RaceConditionDemo:
def __init__(self):
self.shared_var = 0
self.total_count = 100000
self.demo_of_race_condition()

def increment(self):
for i in range(self.total_count):
self.shared_var += 1

def decrement(self):
for i in range(self.total_count):
self.shared_var -= 1

def demo_of_race_condition(self):
t1 = threading.Thread(target=self.increment)
t2 = threading.Thread(target=self.decrement)
t1.start()
t2.start()
t1.join()
t2.join()
print("value of shared_var after all increments & decrements :", self.shared_var)

if __name__ == "__main__":
for i in range(100):
RaceConditionDemo()

The preceding code consists of two methods named increment and decrement that both operate on a single shared variable named shared_var. These two methods are called from separate threads.

One would expect that an equal number of increments and decrements on a shared variable would produce no change in its value at the end. However, when you run this program, say 100 times as before, it produces a different value for the shared variable in each consecutive run. This is a classic example for how a race condition can make the output of a program nondeterministic.

Race conditions occur because we cannot predict the thread execution order at all. The operating system does it very randomly and so the execution order of threads varies each time the program is run.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.62