python 多线程应用介绍
2012-12-19 23:17
411 查看
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多线程在socket编程中的应用(代码范例)
- Python多线程编程方式2 threading库的介绍
- [Python]网络爬虫(四):Opener与Handler的介绍和实例应用
- [Python]网络爬虫(四):Opener与Handler的介绍和实例应用
- [Python]网络爬虫(四):Opener与Handler的介绍和实例应用
- python中多线程中GIL的介绍
- CGI介绍及使用Python来开发CGI应用示例
- 手把手教您Python多线程应用技巧
- c#中跨线程调用windows窗体控件 .我们在做winform应用的时候,大部分情况下都会碰到使用多线程控制界面上控件信息的问题。然而我们并不能用传统方法来做这个问题,下面我将详细的介绍。
- 12.21 python的函数介绍及其应用
- Java.lang.Object类中应用在多线程的几种方法介绍
- Python模块功能在实际应用方案中的相关功能的介绍 分类: database 2014-01-29 16:37 261人阅读 评论(0) 收藏
- [Python]网络爬虫(四):Opener与Handler的介绍和实例应用
- 共享一PYTHON 相关应用领域的介绍资料
- python解释器实现及其嵌入式应用:专栏介绍
- Python模块功能在实际应用方案中的相关功能的介绍
- python3 列表 元组 字典的介绍及其应用
- python应用领域介绍
- python多线程应用——DB2数据库备份