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

相关文章

教女朋友学Python3(二)简单的输入输出及内置函数查看 原创

教女朋友学Python3(二)简单的输入输出及内置函数查看 原创

这是第二天了,工作之余和女朋友一起学Python3,代码都是她敲的,有点辣眼睛,仅做参考。 1.题目:输入“姓名”,输出“你好,姓名” 有关安装和打开Python shell的步骤,参考...

Python将多份excel表格整理成一份表格

利用Python将多份excel表格整理成一份表格,抛弃过去逐份打开复制粘贴的方式。 直接附上代码: import xlrd import xlwt import os fro...

python 搭建简单的http server,可直接post文件的实例

server: #coding=utf-8 from BaseHTTPServer import BaseHTTPRequestHandler import cgi class Po...

Python使用迭代器打印螺旋矩阵的思路及代码示例

Python使用迭代器打印螺旋矩阵的思路及代码示例

思路 螺旋矩阵是指一个呈螺旋状的矩阵,它的数字由第一行开始到右边不断变大,向下变大, 向左变大,向上变大,如此循环。 螺旋矩阵用二维数组表示,坐标(x,y),即(x轴坐标,y轴坐标)。...

python中将一个全部为int的list 转化为str的list方法

假设有这样一个List [1,2,3,4,5] 转化为下面这个样子 [‘1','2','3','4','5'] 解决方法一: a = [1,2,3] b = [ str(i) for...