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 3.6.5 |Anaconda custom (64-bit)| 引言 由于某些原因,需要用python读取二进制文件,这里主要用到struct包,而这...

python正则表达式re模块详解

快速入门 import re pattern = 'this' text = 'Does this text match the pattern?' match = re...

Python2比较当前图片跟图库哪个图片相似的方法示例

本文实例讲述了Python2比较当前图片跟图库哪个图片相似的方法。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- ''' Created on 20...

Opencv+Python 色彩通道拆分及合并的示例

Opencv+Python 色彩通道拆分及合并的示例

一、图像色彩通道拆分 import cv2 img1 = cv2.imread(r"D:\OpencvTest\example.jpg", cv2.IMREAD_COLOR) #...

DJango的创建和使用详解(默认数据库sqlite3)

DJango的创建和使用详解(默认数据库sqlite3)

1.安装虚拟环境 虚拟环境是真实python环境的复制版本。 安装虚拟环境的命令: 1)sudo pip install virtualenv #安装虚拟环境 2)sudo pip in...