Last active
August 13, 2017 03:15
-
-
Save schedutron/ef24f8dbd0001542c756c31d776e4b58 to your computer and use it in GitHub Desktop.
A demo script for threading.Lock
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
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