python 多线程应用介绍

yipeiwu_com6年前Python基础

python可以方便地支持多线程。可以快速创建线程、互斥锁、信号量等等元素,支持线程读写同步互斥。美中不足的是,python的运行在python 虚拟机上,创建的多线程可能是虚拟的线程,需要由python虚拟机来轮询调度,这大大降低了python多线程的可用性。我们经今天用了经典的生产者和消费者的问题来说明下python的多线程的运用 上代码:

#encoding=utf-8 
import threading 
import random 
import time 
from Queue import Queue 

class Producer(threading.Thread): 

def __init__(self, threadname, queue): 
threading.Thread.__init__(self, name = threadname) 
self.sharedata = queue 

def run(self): 
for i in range(20): 
print self.getName(),'adding',i,'to queue' 
self.sharedata.put(i) 
time.sleep(random.randrange(10)/10.0) 
print self.getName(),'Finished' 


# Consumer thread 

class Consumer(threading.Thread): 


def __init__(self, threadname, queue): 
threading.Thread.__init__(self, name = threadname) 
self.sharedata = queue 


def run(self): 

for i in range(20): 
print self.getName(),'got a value:',self.sharedata.get() 
time.sleep(random.randrange(10)/10.0) 
print self.getName(),'Finished' 


# Main thread 

def main(): 

queue = Queue() 
producer = Producer('Producer', queue) 
consumer = Consumer('Consumer', queue) 
print 'Starting threads ...' 
producer.start() 
consumer.start() 
producer.join() 
consumer.join() 
print 'All threads have terminated.' 
if __name__ == '__main__': 
main() 

你亲自运行下这断代码,可能有不一样的感觉!理解以后可以用python cookielib 再结果python urllib 写一个多线程下载网页的脚本应该没什么问题

相关文章

Python基于PycURL自动处理cookie的方法

本文实例讲述了Python基于PycURL自动处理cookie的方法。分享给大家供大家参考。具体如下: import pycurl import StringIO url = "ht...

基于DataFrame筛选数据与loc的用法详解

DataFrame筛选数据与loc用法 python中pandas下的DataFrame是一个很不错的数据结构,附带了许多操作、运算、统计等功能。 如何从一个DataFrame中筛选中出...

解决pandas.DataFrame.fillna 填充Nan失败的问题

如果单独是 >>> df.fillna(0) >>> print(df) # 可以看到未发生改变 >>> print(d...

python实现定时发送qq消息

python实现定时发送qq消息

因为生活中老是忘记各种事情,刚好又在学python,便突发奇想通过python实现提醒任务的功能(尽管TIM有定时功能),也可定时给好友、群、讨论组发送qq消息。其工作流程是:访问数据库...

Python读写Redis数据库操作示例

使用Python如何操作Redis呢?下面用实例来说明用Python读写Redis数据库。比如,我们插入一条数据,如下:复制代码 代码如下:import redisclass Datab...