Created
September 5, 2016 07:10
-
-
Save zhyq0826/4937493628d577cf28604ed0fa7861b5 to your computer and use it in GitHub Desktop.
python 多线程模拟竞态
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
import urllib2 | |
import time | |
from threading import Thread | |
#define a global variable | |
some_var = 0 | |
class IncrementThread(Thread): | |
def run(self): | |
#we want to read a global variable | |
#and then increment it | |
global some_var | |
read_value = some_var | |
print "some_var in %s is %d" % (self.name, read_value) | |
some_var = read_value + 1 | |
print "some_var in %s after increment is %d" % (self.name, some_var) | |
def use_increment_thread(): | |
threads = [] | |
for i in range(50): | |
t = IncrementThread() | |
threads.append(t) | |
t.start() | |
for t in threads: | |
t.join() | |
print "After 50 modifications, some_var should have become 50" | |
print "After 50 modifications, some_var is %d" % (some_var,) | |
if __name__ == '__main__': | |
use_increment_thread() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用锁来解决多线程带来的资源竞争