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() |
import urllib2
import time
from threading import Thread, Lock
#define a global variable
some_var = 0
lock = Lock()
class IncrementThread(Thread):
def run(self):
#we want to read a global variable
#and then increment it
global some_var
lock.acquire()
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)
lock.release()
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()
使用锁来解决多线程带来的资源竞争
- Lock is used to guard against race condition.
- If thread t1 has acquired the lock before performing a set of operations, no other thread can perform the same set of operation until t1 releases the lock.
- We want to make sure that once t1 has read some_var, no other thread can read some_var until t1 is done with modifying the value of some_var.
- So reading some_var and modifying it are logically related operations here.
- And that is why we keep read and modify part of some_var guarded by a Lock instance.
- Lock is a separate object and it will be acquired by the thread from whose context it is called.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation:
Why some_var didn't reach 50?