December 2018
Beginner to intermediate
796 pages
19h 54m
English
Now that we have the tools to start threads and run them, let's simulate a race condition such as the one we discussed earlier:
# race.pyimport threadingfrom time import sleepfrom random import randomcounter = 0randsleep = lambda: sleep(0.1 * random())def incr(n): global counter for count in range(n): current = counter randsleep() counter = current + 1 randsleep()n = 5t1 = threading.Thread(target=incr, args=(n, ))t2 = threading.Thread(target=incr, args=(n, ))t1.start()t2.start()t1.join()t2.join()print(f'Counter: {counter}')
In this example, we define the incr function, which gets a number n in input, and loops over n. In each cycle, it reads the value of the counter, sleeps for a random amount of time (between ...
Read now
Unlock full access