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编程中namedtuple类的用法

Python的Collections模块提供了不少好用的数据容器类型,其中一个精品当属namedtuple。 namedtuple能够用来创建类似于元祖的数据类型,除了能够用索引来访问数...

python用pandas数据加载、存储与文件格式的实例

数据加载、存储与文件格式 pandas提供了一些用于将表格型数据读取为DataFrame对象的函数。其中read_csv和read_talbe用得最多 pandas中的解析函数: 函数...

python点击鼠标获取坐标(Graphics)

python点击鼠标获取坐标(Graphics)

使用Python进行图像编程,要使用到Graphics库。下面列举出较常用的代码 from graphics import * #设置画布窗口名和尺寸 win = Graph...

对django 模型 unique together的示例讲解

unique_together 这个元数据是非常重要的一个!它等同于数据库的联合约束! 举个例子,假设有一张用户表,保存有用户的姓名、出生日期、性别和籍贯等等信息。要求是所有的用户唯一不...

解析Python的缩进规则的使用

Python中的缩进(Indentation)决定了代码的作用域范围。这一点和传统的c/c++有很大的不同(传统的c/c++使用花括号{}符,python使用缩进空格)。 每行代码中开头...