Skip to content

Instantly share code, notes, and snippets.

@coderek
Last active July 25, 2017 02:46
Show Gist options
  • Save coderek/cc88caefbbbdccb6eb5e5d13c4516317 to your computer and use it in GitHub Desktop.
Save coderek/cc88caefbbbdccb6eb5e5d13c4516317 to your computer and use it in GitHub Desktop.
threading and synchronization
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