Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Results are not matching in Chapter 1 example 2 #4

Open
UsNizami opened this issue Jun 7, 2023 · 1 comment
Open

Results are not matching in Chapter 1 example 2 #4

UsNizami opened this issue Jun 7, 2023 · 1 comment

Comments

@UsNizami
Copy link

UsNizami commented Jun 7, 2023

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 ?

@Matej-Chmel
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants