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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you waiting long enough you will see same problems happens in Python3