我尝试从“Programming Python”Mark Lutz运行简单的代码。当我从IDLE跑出来时,一切都很好。当我从命令行运行时脚本不起作用 - 没有输出,任何错误,只是在time.sleep()
中定义的时间之后完成。
如何从命令行正确运行此脚本? 我正在使用Ubuntu。
import Queue, thread, time
producersnumber=3
consumersnumber=1
msgnum=3
dataqueue=Queue.Queue()#why double
safeprint=thread.allocate_lock()
def producer(no):
for i in range(msgnum):
p='signalfrom %s'%no
time.sleep(1)
dataqueue.put(p)
def consumer(no):
while 1:
time.sleep(1)
try:
data=dataqueue.get(block=False)
except Queue.Empty:
pass
else:
safeprint.acquire()
print data
safeprint.release()
if __name__=='__main__':
for i in range(consumersnumber):
thread.start_new_thread(consumer,(i,))
for i in range(producersnumber):
thread.start_new_thread(producer,(i,))
time.sleep(1)
答案 0 :(得分:1)
Your time.sleep(1)
, in the last line, will kill the threads by program exit before they actually do anything (as the producer waits for a second before sending anything). Change that line to time.sleep(10)
or diminish the values for time.sleep()
that you have in the producer
or consumer
.
With time.sleep(10)
you'll get:
signalfrom 1
signalfrom 0
signalfrom 2
signalfrom 1
signalfrom 0
signalfrom 2
signalfrom 1
signalfrom 0
signalfrom 2