Skip to content

Instantly share code, notes, and snippets.

@eagafonov
Created October 8, 2017 21:17
Show Gist options
  • Save eagafonov/73957cf3d1dde3029a7ed54bfa88f0fd to your computer and use it in GitHub Desktop.
Save eagafonov/73957cf3d1dde3029a7ed54bfa88f0fd to your computer and use it in GitHub Desktop.
'''
Run as
> python3 gil_vs_threads.py 2> /dev/null
'''
import threading
import sys
the_value = 0
def do_read_update(input_output):
global the_value
# Read
old_value = the_value
if input_output:
sys.stderr.write('.')
sys.stderr.flush()
# Modify
the_value = old_value + 1
def thread_func(input_output):
for _ in range(1000):
do_read_update(input_output)
if __name__ == '__main__':
input_output = True
print("Creating threads")
threads = [ threading.Thread(target=thread_func, args=(input_output,)) for _ in range(100)]
print("Starting threads")
for t in threads:
t.start()
print("Waiting threads")
for t in threads:
t.join()
print("Final value:", the_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment