Skip to content

Instantly share code, notes, and snippets.

@schedutron
Last active August 13, 2017 03:15
Show Gist options
  • Save schedutron/ef24f8dbd0001542c756c31d776e4b58 to your computer and use it in GitHub Desktop.
Save schedutron/ef24f8dbd0001542c756c31d776e4b58 to your computer and use it in GitHub Desktop.
A demo script for threading.Lock
from threading import Lock, Thread
lock = Lock()
g = 0
def add_one():
global g # Just used for demonstration. It’s bad to use the ‘global’ statement in general.
lock.acquire()
g += 1
lock.release()
def add_two():
global g
lock.acquire()
g += 2
lock.release()
threads = []
for func in [add_one, add_two]:
threads.append(Thread(target=func))
threads[-1].start()
for thread in threads: # Waits for threads to complete before moving on with the main script.
thread.join()
print(g)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment