搜索
首页后端开发Python教程深入理解 Python 中的多线程 新手必看

示例1
我们将要请求五个不同的url:
单线程

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()

输出是:
http://www.baidu.com200
http://www.amazon.com200
http://www.ebay.com200
http://www.alibaba.com200
http://www.jb51.net200
Elapsed time:3.0814409256

解释:
url顺序的被请求
除非cpu从一个url获得了回应,否则不会去请求下一个url
网络请求会花费较长的时间,所以cpu在等待网络请求的返回时间内一直处于闲置状态。
多线程

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.amazon.com',     
‘http://www.ebay.com',     
‘http://www.alibaba.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()

输出:
http://www.jb51.net200
http://www.baidu.com200
http://www.amazon.com200
http://www.alibaba.com200
http://www.ebay.com200
Elapsed time:0.689890861511

解释:

意识到了程序在执行时间上的提升
我们写了一个多线程程序来减少cpu的等待时间,当我们在等待一个线程内的网络请求返回时,这时cpu可以切换到其他线程去进行其他线程内的网络请求。
我们期望一个线程处理一个url,所以实例化线程类的时候我们传了一个url。
线程运行意味着执行类里的run()方法。
无论如何我们想每个线程必须执行run()。
为每个url创建一个线程并且调用start()方法,这告诉了cpu可以执行线程中的run()方法了。
我们希望所有的线程执行完毕的时候再计算花费的时间,所以调用了join()方法。
join()可以通知主线程等待这个线程结束后,才可以执行下一条指令。
每个线程我们都调用了join()方法,所以我们是在所有线程执行完毕后计算的运行时间。

关于线程:

cpu可能不会在调用start()后马上执行run()方法。
你不能确定run()在不同线程建间的执行顺序。
对于单独的一个线程,可以保证run()方法里的语句是按照顺序执行的。
这就是因为线程内的url会首先被请求,然后打印出返回的结果。

实例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()

多次运行这个程序,你会看到多种不同的结果。
解释:
有一个全局变量,所有的线程都想修改它。
所有的线程应该在这个全局变量上加 1 。
有50个线程,最后这个数值应该变成50,但是它却没有。
为什么没有达到50?
在some_var是15的时候,线程t1读取了some_var,这个时刻cpu将控制权给了另一个线程t2。
t2线程读到的some_var也是15
t1和t2都把some_var加到16
当时我们期望的是t1 t2两个线程使some_var + 2变成17
在这里就有了资源竞争。
相同的情况也可能发生在其它的线程间,所以出现了最后的结果小于50的情况。
解决资源竞争

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, read_value)     
some_var=read_value+1    
print”some_var in %s after increment 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, some_var should have become 50″   
print”After 50 modifications, some_var is %d”%(some_var,)    
use_increment_thread()

再次运行这个程序,达到了我们预期的结果。
解释:
Lock 用来防止竞争条件
如果在执行一些操作之前,线程t1获得了锁。其他的线程在t1释放Lock之前,不会执行相同的操作
我们想要确定的是一旦线程t1已经读取了some_var,直到t1完成了修改some_var,其他的线程才可以读取some_var
这样读取和修改some_var成了逻辑上的原子操作。
实例3
让我们用一个例子来证明一个线程不能影响其他线程内的变量(非全局变量)。
time.sleep()可以使一个线程挂起,强制线程切换发生。

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是个逻辑上的原子操作,以防打印时被其他线程打断。
我们使用了Lock(),来看下边的例子。

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()

这次我们看到了正确的结果。证明了一个线程不可以修改其他线程内部的变量(非全局变量)。

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表的内存足迹与python数组的内存足迹相比如何?列表的内存足迹与python数组的内存足迹相比如何?May 02, 2025 am 12:08 AM

列表sandnumpyArraysInpyThonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,withoverHeadeBheadaroundAroundaroundaround64bytaround64bitson64-bitsysysysyssyssyssyssyssyssysssys2)

部署可执行的Python脚本时,如何处理特定环境的配置?部署可执行的Python脚本时,如何处理特定环境的配置?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehavecorrectlyacrycrossdevelvermations,登台和生产,USETHESTERTATE:1)Environment varriablesforsimplesettings,2)configurationFilesForefilesForcomPlexSetups,3)dynamiCofforAdaptapity.eachmethodofferSuniquebeneiquebeneiquebeneniqueBenefitsaniqueBenefitsandrefitsandRequiresandRequireSandRequireSca

您如何切成python阵列?您如何切成python阵列?May 01, 2025 am 12:18 AM

Python列表切片的基本语法是list[start:stop:step]。1.start是包含的第一个元素索引,2.stop是排除的第一个元素索引,3.step决定元素之间的步长。切片不仅用于提取数据,还可以修改和反转列表。

在什么情况下,列表的表现比数组表现更好?在什么情况下,列表的表现比数组表现更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/删除,2)储存的二聚体和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何将Python数组转换为Python列表?如何将Python数组转换为Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,请考虑performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!