Simulating race conditions in Python
If you have already downloaded the code for this book from the GitHub page, go ahead and navigate to the Chapter14
folder.
To simulate a race condition, first, we need a common resource. In this case, it's a counter variable along with multiple threads that can access it simultaneously. Let's take a look at the Chapter14/example1.py
file—specifically, the update()
function, as follows:
import random import time def update(): global counter current_counter = counter # reading in shared resource time.sleep(random.randint(0, 1)) # simulating heavy calculations counter = current_counter + 1 # updating shared resource
The goal of the preceding update()
function is to increment a global variable called counter
, and it is to be called by a separate thread in our script. Inside the function...