最近用python处理一个消息队列的问题 所有功能都完善了 到现在还有一个没有解决的问题就是 当服务打开后 无法使用ctrl+c 或者发送结束的single结束 每次都要kill进程号才可以 不知道有没有更好的办法
消息队列结构代码如下:对线程其实还是有点迷糊的 指导下 谢谢。
#encoding=utf-8
import threading
import random
import time
from Queue import Queue
class Producer(threading.Thread):
    def __init__(self, threadname, queue):
        threading.Thread.__init__(self, name = threadname)
        self.sharedata = queue
    def run(self):
        while True:
            for i in range(20):
                print self.getName(),'adding',i,'to queue'
                self.sharedata.put(i)
                time.sleep(random.randrange(10)/10.0)
            time.sleep(8)
            print '======== NEW ==========='
        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):
        while True:
            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()