python核心编程-线程threading模块之生产者与消费者
来源:互联网 发布:apache spark 版本 编辑:程序博客网 时间:2024/05/21 20:22
myThread.py
编译成模块:python -O -m py_compile myThread.py
#!/usr/bin/env python# -*- coding: UTF-8 -*- ''' function :线程模块threading 仅练习'''from time import sleep, ctimeimport threadingloops = (4, 2)class MyThread(threading.Thread): def __init__(self, func, args, name=''): threading.Thread.__init__(self) self.name = name self.func = func self.args = args def getResult(self): return self.res def run(self): print 'staring', self.name, 'at:', ctime() self.res = apply(self.func, self.args) print self.name, 'finished at:', ctime()
#!/usr/bin/env python# -*- coding: UTF-8 -*- ''' function :线程模块threading 仅练习'''from myThread import MyThreadfrom time import sleepfrom random import randintfrom Queue import Queuedef writeQ(queue): print 'producing object for Q...', queue.put('xxx', 1) print "size now", queue.qsize()def readQ(queue): val = queue.get(1) print 'consumed object from Q... size now', queue.qsize()def writer(queue, loops): for i in range(loops): writeQ(queue) sleep(randint(1, 3))def reader(queue, loops): for i in range(loops): readQ(queue) sleep(randint(2, 5))funcs = [writer, reader]nfuncs = range(len(funcs))def main(): nloops = randint(2, 5) q = Queue(32) threads = [] for i in nfuncs: t = MyThread(funcs[i], (q, nloops), funcs[i].__name__) threads.append(t) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join() print 'all DONE'if __name__ == '__main__': main()
输出:
D:\Python27\test>thread09.py
staring staringwriter readerat: at:Wed Jan 20 23:11:18 2016 Wed Jan 20 23:11:18 2016
producing object for Q… consumed object from Q… size nowsize now 00
producing object for Q… consumed object from Q… size nowsize now 00
producing object for Q… size now 1
consumed object from Q… size now 0
producing object for Q… size now 1
consumed object from Q… size nowproducing object for Q… size now 1
1
writer finished at: Wed Jan 20 23:11:28 2016
consumed object from Q… size now 0
reader finished at: Wed Jan 20 23:11:35 2016
all DONE
D:\Python27\test>
0 0
- python核心编程-线程threading模块之生产者与消费者
- python核心编程-线程之threading模块
- [Python]核心编程之生产者-消费者和Queue模块
- python核心编程-线程threading模块之三
- python核心编程-线程threading模块之四
- python核心编程-线程threading模块二
- python核心编程-线程threading模块之单线程多线比较
- 利用python线程编程实现生产者与消费者关系
- 线程与threading模块(python)
- python使用threading.condition实现生产者消费者
- java线程经典之生产者与消费者
- java线程之生产者与消费者模式
- 在python中实现生产者和消费者的例子(五):使用threading模块和全局变量
- python多线程(3)---生产者与消费者(线程通信)和Queue模块
- 线程生产者与消费者
- 线程---生产者与消费者
- 线程之“生产者消费者”
- 线程之生产者消费者
- java生成验证码
- DOM简单介绍
- Spark 阶段总结 1
- 单片机轻松入门之一点亮一个发光二极管
- Gallery实现图片文字左右滑动放大当前选中
- python核心编程-线程threading模块之生产者与消费者
- 类
- 【Android】获取控件的宽和高
- 重排链表
- 1.1 Git的本地使用详解
- Spark 阶段总结 2
- Document对象的使用:getElementById()和getElementsByTagName()方法的使用练习
- .PHONY makefile中的伪目标
- 装ghost遇到的问题之一“Windows failed to start. A Recent hardware or software change might be the cause.”