Simulating race conditions in Python
Before we discuss a solution that we can implement to solve the problem of race conditions, let's try to simulate the problem in Python. If you have already downloaded the code for this book from the GitHub page, go ahead and navigate to the Chapter21
folder. Let's take a look at the Chapter21/example1.py
file—specifically, the update()
function, as follows:
# Chapter21/example1.py 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, we are interacting with a shared resource—in this case, counter
. We then assign the value of counter
to another local variable, called current_counter
(this...