max time threads
pacopyc
pacopyc at gmail.com
Thu Jun 17 17:52:45 EDT 2010
Hi, I'm trying to work with threads and I need your help. This is
code:
from threading import Thread
from Queue import Queue
import time
import random
def test_fun (k,q,t):
time.sleep(t)
print "hello world from thread " + str(q.get()) + " (sleep time =
" + str(t) + " sec.)"
q.task_done()
queue = Queue()
for i in range (1,10):
queue.put(i)
for j in range(queue.qsize()):
num = random.randint(1,30)
worker = Thread(target=test_fun, args=(j,queue,num))
worker.setDaemon(True)
worker.start()
queue.join()
Execution:
hello world from thread 1 (sleep time = 5 sec.)
hello world from thread 2 (sleep time = 5 sec.)
hello world from thread 3 (sleep time = 6 sec.)
hello world from thread 4 (sleep time = 8 sec.)
hello world from thread 5 (sleep time = 10 sec.)
hello world from thread 6 (sleep time = 13 sec.)
hello world from thread 7 (sleep time = 18 sec.)
hello world from thread 8 (sleep time = 19 sec.)
hello world from thread 9 (sleep time = 20 sec.)
Some questions for you:
1) Why order is always the same (thread 1, thread 2, thread 3 ....
thread 9) and also seconds are always increasing? I don't understand.
2) I'd like to decide a max time for each thread. If max time = 7 sec.
I want to print only threads with sleep time <= 7 sec. How can I do?
Can you modify my code?
Thank you very much
More information about the Python-list
mailing list