我找到了一个用两个线程表示生产者-消费者的例子。但是,当我向进程发送停止信号时,它没有。它期待第二个信号,例如SIGKILL完全停止。我以为问题出在,task_done()但似乎不是。import timeimport queueimport threadingimport randomclass Producer(threading.Thread): """ Produces random integers to a list """ def __init__(self, queue): """ Constructor. @param queue queue synchronization object """ threading.Thread.__init__(self) self.queue = queue def run(self): """ Thread run method. Append random integers to the integers list at random time. """ while True: integer = random.randint(0, 256) self.queue.put(integer) print('%d put to queue by %s' % (integer, self.name)) time.sleep(1)class Consumer(threading.Thread): """ Consumes random integers from a list """ def __init__(self, queue): """ Constructor. @param integers list of integers @param queue queue synchronization object """ threading.Thread.__init__(self) self.queue = queue def run(self): """ Thread run method. Consumes integers from list """ while True: integer = self.queue.get() print('%d popped from list by %s' % (integer, self.name)) self.queue.task_done()def main(): q = queue.Queue() t1 = Producer(q) t2 = Consumer(q) t1.start() t2.start() t1.join() t2.join()if __name__ == '__main__': main()输出:210 put to queue by Thread-1210 popped from list by Thread-2Traceback (most recent call last): File "/Users/abc/PycharmProjects/untitled1/ssid.py", line 74, in <module> main() File "/Users/abc/PycharmProjects/untitled1/ssid.py", line 69, in main t1.join()
添加回答
举报
0/150
提交
取消