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

相关文章

Python中的if、else、elif语句用法简明讲解

下面我们学习if语句,输入下面的代码,确保能够正确运行。 people = 20 cats = 30 dogs = 15 if people < cats:...

安装Python的教程-Windows

安装Python的教程-Windows

在开始Python编程前,需要先安装Python环境。Python安装包可以到Python的官网下载,官网地址是https://www.python.org/,如果想直接跳过关于Pyth...

Python 实现大整数乘法算法的示例代码

我们平时接触的长乘法,按位相乘,是一种时间复杂度为 O(n ^ 2) 的算法。今天,我们来介绍一种时间复杂度为 O (n ^ log 3) 的大整数乘法(log 表示以 2 为底的对数)...

Python测试线程应用程序过程解析

这篇文章主要介绍了Python测试线程应用程序过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在本章中,我们将学习线程应用程序...

python绘制彩虹图

python绘制彩虹图

本文实例为大家分享了python绘制彩虹图的具体代码,供大家参考,具体内容如下 from turtle import * #控制彩虹路径 def path(pen, r, g,...