金源在线客服

在线咨询

QQ在线咨询

QQ咨询

01Jan

使用Queue实现生产者和消费者

from Queue import Queue
import threading
import random
import time

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(10):
            print self.getName(), 'adding', i, 'to queue'
            self.sharedata.put(i)
            time.sleep(random.randrange(10)/10.0)
        print self.getName(), 'Finished'
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(10):
            print self.getName(), 'get a value', self.sharedata.get()
            time.sleep(random.randrange(10)/10.0)
        print self.getName(), 'Finished'
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()

 

如何来获得与线程有关的信息呢?

获得当前正在运行的线程的引用

running = threading.currentThread()

获得当前所有活动对象(即run方法开始但是未终止的任何线程)的一个列表

threadlist = threading.enumerate()

获得这个列表的长度

threadcount = threading.activeCount()

查看一个线程对象的状态调用这个线程对象的isAlive()方法,返回1代表处于“runnable”状态且没有“dead

threadflag = threading.isAlive()

上一篇:dictionary 的字符串格式化
下一篇:Django全局context处理器