Created
July 17, 2018 09:03
-
-
Save laixintao/fcfef35fd99d4236612fcc8309c0bd4e to your computer and use it in GitHub Desktop.
This file contains 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
# -*- 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) |
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
It seems Python2.7 are different from Python3: