MartinP MartinP - 5 months ago 18
Python Question

Script with threads working in IDLE but not by command line Ubuntu

I try run simple code from "Programming Python" Mark Lutz. When I run from IDLE everything's allright. When I run from command line script doesn't work - no output, any bugs, just finished after time defined in

time.sleep()
.

How can I run this script correctly from the command line?
I'm working with 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)

Answer

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 second before sending anything). Change that line to time.sleep(10) or deminish 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