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
原创粉丝点击