Python论坛  - 讨论区

标题:[python-chinese] python 同步队列的问题

2007年07月16日 星期一 17:39

leopay leopay在gmail.com
星期一 七月 16 17:39:47 HKT 2007

ÏÂÃæÕâ¶Î´úÂëÔõôÔËÐеÄʱºò£¬ÔõôÓÐʱºò»á³öÏÖ
Consumer got a value: Producer Finished
Producer adding 17 to queue
17
Consumer Finished
Consumer got a value: Producer Finished
Producer adding 18 to queue
18
Producer Finished

¾ÍÊÇ˵ÔÚprintµÄʱºò£¬Óеã´íÂÒ


# queue_example.py
from Queue import Queue
import threading
import random
import time

# Producer thread
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()
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070716/e6abfd6c/attachment.htm 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号