This is my first attempt at threads in Python ... And it worked with greed :) I wanted to implement the main problem with the critical zone and found that this code does not actually represent a problem.
Question: why I have no problems with incrementing the counter? Doesn't the counter have random values ββafter the run? I can only explain this if the increment is already running atomically or if the threads are not parallel ...
import threading import time turnstile_names = ["N", "E", "S", "W"] count = 0 class Counter(threading.Thread): def __init__(self, id): threading.Thread.__init__(self) self.id = id def run(self): global count for i in range(20):
Notes. I left comments on acquire() and release() to check the difference. I tried to skip the thread by adding a little sleep after the increment - no difference
Solution / tests: Thanks, Kevin (see accepted answer below). I just tested changing a loop variable and got the following:
Loops Result 20 99% of the time 80. Sometimes 60. 200 99% of the time 800. Sometimes 600. 2000 Maybe 10% of the time different value 20000 Finally... random numbers! I've yet to see 80000 or 60000. All numbers are now random, as originally expected.
I suspect that this apparently means that the flow overhead is in the order of 10 ^ 4 increment operations.
Another interesting test (well, at least in my opinion):
I added time.sleep(random.random()/divisor) after the increment and found when the number of loops is again 20:
divisor result 100 always 4, so the race condition is always there. 1000 95% of the time 4, sometimes 3 or 5 (once 7) 10000 99% of the time NOT 4, varying from 4 to 13 100000 basically same as 10000 1000000 varying from 10 to 70 10000000... same as previous... (even with time.sleep(0))
source share