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学习笔记之迭代器和生成器用法实例详解

本文实例讲述了Python学习笔记之迭代器和生成器用法。分享给大家供大家参考,具体如下: 迭代器和生成器 迭代器 每次可以返回一个对象元素的对象,例如返回一个列表。我们到目前为止使...

Python os.access()用法实例

概述 os.access() 方法使用当前的uid/gid尝试访问路径。大部分操作使用有效的 uid/gid, 因此运行环境可以在 suid/sgid 环境尝试。 语法 acces...

浅析使用Python操作文件

1. file=open('xxx.txt', encoding='utf-8'),open()函数是Python内置的用于对文件的读写操作,返回的是文件的流对象(而不是文件本身,所以使...

Python中字典(dict)和列表(list)的排序方法实例

一、对列表(list)进行排序 推荐的排序方式是使用内建的sort()方法,速度最快而且属于稳定排序复制代码 代码如下:>>> a = [1,9,3,7,2,0,5]&...

从0开始的Python学习014面向对象编程(推荐)

从0开始的Python学习014面向对象编程(推荐)

简介 到目前为止,我们的编程都是根据数据的函数和语句块来设计的,面向过程的编程。还有一种我们将数据和功能结合起来使用对象的形式,使用它里面的数据和方法这种方法叫做面向对象的编程。 类和对...