py 使用MyThread继承重写线程类实现多线程编程

来源:互联网 发布:网络交往具有什么特点 编辑:程序博客网 时间:2024/06/10 20:04

MyThread.py

# import threadingfrom time import time, ctimeclass 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 'starting', self.name, 'at:', \    ctime()        self.res = apply(self.func, self.args)        print self.name, 'finished at:', \    ctime()

实现生产者--消费者。演示。

# from random import randintfrom time import sleepfrom Queue import Queuefrom myThread import MyThreaddef writeQ(queue):#write 1    print 'in the writing:'    print 'producing object for Q...',    queue.put('xxx', 1)    print "size now", queue.qsize()    print 'get out of the writing.'def readQ(queue):#read 1    print 'in the reading:'    val = queue.get(1)    print 'consumed object from Q... size now', queue.qsize()    print 'get out of the reading'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]funcs=[reader,writer]nfuncs = range(len(funcs))def main():    nloops = randint(2, 5)    q = Queue(32)    print 'nloops=',nloops    threads = []    for i in nfuncs:        t = MyThread(funcs[i], (q, nloops), funcs[i].__name__)        #          [writer, reader]        threads.append(t)    for i in nfuncs:        threads[i].start()    for i in nfuncs:        threads[i].join()    print 'all DONE'if __name__ == '__main__':    main()

结果:为了表现出矛盾 我把read(消费者)放到了第一个线程里面,这样会出现一个消费者不能消费的情况。

nloops= 4starting reader at: Sun Dec 28 21:03:02 2014in the reading:starting writer at: Sun Dec 28 21:03:02 2014in the writing:producing object for Q... size now 1get out of the writing.consumed object from Q... size now 0get out of the readingin the writing:producing object for Q... size now 1get out of the writing.in the reading:consumed object from Q... size now 0get out of the readingin the writing:producing object for Q... size now 1get out of the writing.in the writing:producing object for Q... size now 2get out of the writing.in the reading:consumed object from Q... size now 1get out of the readingwriter finished at: Sun Dec 28 21:03:10 2014in the reading:consumed object from Q... size now 0get out of the readingreader finished at: Sun Dec 28 21:03:14 2014all DONE






0 0