Mastering-Concurrency-in-Python
Mastering-Concurrency-in-Python copied to clipboard
Results are not matching in Chapter 1 example 2
In example 2 of chapter 1. When I run the file I get
Result is very large. Only printing the last 5 digits: 35443 Sequential took: 0.05 seconds. Result is very large. Only printing the last 5 digits: 45807 Concurrent took: 0.02 seconds.
but 35433 is not equal to 45807. The results should be equal to 35443. What is the issue here ?
The lack of synchronization in the script enables the interpreter to switch threads in the middle of the computation of the f
function. This race condition sometimes makes the script to report the wrong result.
You can solve this issue by applying a lock:
import threading
def concurrent_f(x):
global result
with lock:
result = f(result)
lock = threading.Lock()
Or by increasing the switch interval at the beginning of the script:
import sys
sys.setswitchinterval(1) # The default is 0.005 (5 ms)
This is not ideal solution but it doesn't modify the original concurrent_f
function.