#!/usr/bin/python
import threading
from time import ctime, sleep
from Queue import Queue
from random import randint
class WadeThread(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.result
def run(self):
print 'starting', self.name, 'at:', ctime()
self.result = apply(self.func, self.args)
print self.name, 'finished at:', ctime()
def produce(queue, loops):
for i in range(loops):
sleep(randint(0, 2))
queue.put('192.168.102.x', 1)
print 'producing object for Q... size now', queue.qsize()
def consume(queue, loops):
for i in range(loops):
sleep(randint(2, 5))
o = queue.get(1)
print 'consumed object from Q... size now', queue.qsize()
funcs = [produce, consume]
def main():
q = Queue(1000)
threads = []
for i in range(len(funcs)):
t = WadeThread(funcs[i], (q, 10))
threads.append(t)
for i in range(len(funcs)):
threads[i].start()
for i in range(len(funcs)):
threads[i].join()
if __name__ == '__main__':
main()
生产消费者简单实现
最新推荐文章于 2024-06-29 18:57:11 发布