打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python 多线程应用介绍

python 多线程应用介绍

 
发布:mdxy-dxy 字体:[增加 减小] 类型:转载
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 写一个多线程下载网页的脚本应该没什么问题
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python多线程学习(三、生产者与消费者)
Python线程编程
用Python多线程实现生产者消费者模式
python多线程编程(6): 队列同步
python数据结构:多线程数据处理,优先级队列--Queue
python爬虫14 | 就这么说吧,如果你不懂python多线程和线程池,那就去河边摸鱼!
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服