February 2019
Intermediate to advanced
672 pages
16h 50m
English
Now, let's implement the specification in the preceding example, in order to solve the problem of race conditions. Navigate to the Chapter21/example2.py file and consider our corrected update() function, as follows:
# Chapter21/example2.pyimport randomimport timedef update(): global counter with count_lock: current_counter = counter # reading in shared resource time.sleep(random.randint(0, 1)) # simulating heavy calculations counter = current_counter + 1
You can see that all of the execution instructions of a thread specified in the update() function are under the context manager of a lock object named count_lock. So, every time a thread is called to run the function, it will have to first acquire the lock object, ...