Last active
July 25, 2017 02:46
-
-
Save coderek/cc88caefbbbdccb6eb5e5d13c4516317 to your computer and use it in GitHub Desktop.
threading and synchronization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from random import random | |
from threading import Thread, Lock | |
""" | |
Python's GIL ensures that non IO ops will execute sequentially | |
So no need to sync the followings | |
s = store + 1 | |
store = s | |
""" | |
l = Lock() | |
store = 0 | |
def doit(): | |
with l: | |
global store | |
s = store + 1 | |
time.sleep(random()) # IO op | |
store = s | |
threads = [] | |
for i in range(10): | |
t = Thread(target=doit) | |
t.start() | |
threads.append(t) | |
# without synchronization, this takes about 1 sec | |
# with synchronization, this takes 10 sec | |
time.sleep(1) | |
for t in threads: | |
t.join() | |
print(store) # 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment