深入理解 Python 中的多线程 新手必看
|
示例1
import time
import urllib2
defget_responses():
urls=[
‘http://www.baidu.com',‘http://www.amazon.com',‘http://www.ebay.com',‘http://www.alibaba.com',‘http://www.jb51.net'
]
start=time.time()
forurlinurls:
printurl
resp=urllib2.urlopen(url)
printresp.getcode()
print”Elapsed time: %s”%(time.time()-start)
get_responses()
输出是: 解释:
import urllib2
import time
from threading import Thread
classGetUrlThread(Thread):
def__init__(self,url):
self.url=url
super(GetUrlThread,self).__init__()
defrun(self):
resp=urllib2.urlopen(self.url)
printself.url,resp.getcode()
defget_responses():
urls=[
‘http://www.baidu.com',‘http://www.jb51.net'
]
start=time.time()
threads=[]
forurlinurls:
t=GetUrlThread(url)
threads.append(t)
t.start()
fortinthreads:
t.join()
print”Elapsed time: %s”%(time.time()-start)
get_responses()
输出: 解释: 意识到了程序在执行时间上的提升 关于线程: cpu可能不会在调用start()后马上执行run()方法。 实例2 我们将会用一个程序演示一下多线程间的资源竞争,并修复这个问题。
from threading import Thread
#define a global variable
some_var=0
classIncrementThread(Thread):
defrun(self):
#we want to read a global variable
#and then increment it
globalsome_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)
defuse_increment_thread():
threads=[]
foriinrange(50):
t=IncrementThread()
threads.append(t)
t.start()
fortinthreads:
t.join()
print”After 50 modifications,some_var should have become 50″
print”After 50 modifications,some_var is %d”%(some_var,)
use_increment_thread()
多次运行这个程序,你会看到多种不同的结果。
from threading import Lock,Thread
lock=Lock()
some_var=0
classIncrementThread(Thread):
defrun(self):
#we want to read a global variable
#and then increment it
globalsome_var
lock.acquire()
read_value=some_var
print”some_var in %s is %d”%(self.name,some_var)
lock.release()
defuse_increment_thread():
threads=[]
foriinrange(50):
t=IncrementThread()
threads.append(t)
t.start()
fortinthreads:
t.join()
print”After 50 modifications,)
use_increment_thread()
再次运行这个程序,达到了我们预期的结果。
from threading import Thread
import time
classCreateListThread(Thread):
defrun(self):
self.entries=[]
foriinrange(10):
time.sleep(1)
self.entries.append(i)
printself.entries
defuse_create_list_thread():
foriinrange(3):
t=CreateListThread()
t.start()
use_create_list_thread()
运行几次后发现并没有打印出争取的结果。当一个线程正在打印的时候,cpu切换到了另一个线程,所以产生了不正确的结果。我们需要确保print self.entries是个逻辑上的原子操作,以防打印时被其他线程打断。
from threading import Thread,Lock
import time
lock=Lock()
classCreateListThread(Thread):
defrun(self):
self.entries=[]
foriinrange(10):
time.sleep(1)
self.entries.append(i)
lock.acquire()
printself.entries
lock.release()
defuse_create_list_thread():
foriinrange(3):
t=CreateListThread()
t.start()
use_create_list_thread()
这次我们看到了正确的结果。证明了一个线程不可以修改其他线程内部的变量(非全局变量)。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
