Python队列同步

来源:互联网 发布:淘宝怎么查看我的评价 编辑:程序博客网 时间:2024/05/16 17:53

Python的Queue模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列PriorityQueue。这些队列都实现了锁原语,能够在多线程中直接使用。可以使用队列来实现线程间的同步。

import threadingimport timefrom Queue import Queueclass Producer(threading.Thread):        def run(self):                global queue                count=0                while True:                        for i in range(100):                                if queue.qsize()>1000:                                        pass                                else:                                        count=count+1                                        msg='produce'+str(count)                                        queue.put(msg)                                        print msg                        time.sleep(1)class Consumer(threading.Thread):        def run(self):                global queue                while True:                        for i in range(3):                                if queue.qsize()<100:                                        pass                                else:                                        msg=self.name+'consume'+queue.get()                                        print msg                        time.sleep(1)queue=Queue()def test():        for i in range(500):                queue.put('init produce'+str(i))        for i in range(2):                p=Producer()                p.start()        for i in range(5):                c=Consumer()                c.start()if __name__=='__main__':        test()


原创粉丝点击