python 多线程应用介绍

yipeiwu_com5年前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 写一个多线程下载网页的脚本应该没什么问题

相关文章

django框架auth模块用法实例详解

django框架auth模块用法实例详解

本文实例讲述了django框架auth模块用法。分享给大家供大家参考,具体如下: auth模块的导入 from django.contrib import auth django中...

python Dijkstra算法实现最短路径问题的方法

本文借鉴于张广河教授主编的《数据结构》,对其中的代码进行了完善。 从某源点到其余各顶点的最短路径 Dijkstra算法可用于求解图中某源点到其余各顶点的最短路径。假设G={V,{E}}...

python提示No module named images的解决方法

本文讲述了python提示No module named images的解决方法,非常实用!分享给大家供大家参考。具体方法如下: 出现提示:ImportError: No module...

Python中的pathlib.Path为什么不继承str详解

起步 既然所有路径都可以表示为字符串,为什么 pathlib.Path 不继承 str ? 这个想法的提出在 https://mail.python.org/pipermail...

详解多线程Django程序耗尽数据库连接的问题

Django的ORM是非常好用的,哪怕不是做Web项目也值得一用,所以网上也可以找到不少使用 Django 开发非Web项目的资料,因为除了ORM之个,命令行、配置文件等组件也非常好用。...