Skip to content

Instantly share code, notes, and snippets.

@laixintao
Created July 17, 2018 09:03
Show Gist options
  • Save laixintao/fcfef35fd99d4236612fcc8309c0bd4e to your computer and use it in GitHub Desktop.
Save laixintao/fcfef35fd99d4236612fcc8309c0bd4e to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
Since we have GIL, should we add Lock for global variable read/write?
"""
import threading
shared_resource_with_no_lock = 0
COUNT = 100000
def increment_without_lock():
global shared_resource_with_no_lock
for i in range(COUNT):
shared_resource_with_no_lock += 1
def decrement_without_lock():
global shared_resource_with_no_lock
for i in range(COUNT):
shared_resource_with_no_lock -= 1
while 1:
t3 = threading.Thread(target=increment_without_lock)
t4 = threading.Thread(target=decrement_without_lock)
t3.start()
t4.start()
t3.join()
t4.join()
print(shared_resource_with_no_lock)
@laixintao
Copy link
Author

If you waiting long enough you will see same problems happens in Python3


0
0
0
0
0
0
0
0
0
0
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
-40611
^CTraceback (most recent call last):
  File "multi.py", line 31, in <module>
    t4.join()
  File "/usr/local/var/pyenv/versions/3.7.0/lib/python3.7/threading.py", line 1032, in join
    self._wait_for_tstate_lock()
  File "/usr/local/var/pyenv/versions/3.7.0/lib/python3.7/threading.py", line 1048, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt
➜

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment