2013-04-11 152 views
5

我想写一个程序,它在循环中创建新线程,并不等待它们完成。 据我了解,如果我在线程上使用.start(),我的主循环应该继续,而另一个线程将关闭并同时完成其工作蟒蛇线程块

但是,一旦我的新线程启动,循环块直到线程完成。 我误解了线程是如何在python中工作的,或者是我在做什么愚蠢的事情。

这里是我创建新主题的代码。

def MainLoop(): 
    print 'started' 
    while 1: 
     if not workQ.empty(): 
      newThread = threading.Thread(target=DoWorkItem(), args=()) 
      newThread.daemon = True 
      newThread.start() 
     else: 
      print 'queue empty' 

感谢所有

回答

12

这调用该函数并将其结果target

threading.Thread(target=DoWorkItem(), args=()) 

失去了括号来传递函数对象本身:

threading.Thread(target=DoWorkItem, args=()) 
+0

哈哈,我犯了同样的愚蠢错误^^。谢谢! – 2015-06-17 20:09:20

-3

我不喜欢使用队列。你可以尝试我的方法:

import threading 
import time 

THREAD_NUM = 5 

def f(x): 
    if x > 20 and x < 30: 
     time.sleep(5) 
    print 'params: %s \n' % x 

if __name__ == '__main__': 
    queue_list = range(100) 
    for params in queue_list: 
     while True: 
      if threading.active_count() < THREAD_NUM: 
       break 
     threading.Thread(target=f, args=(params,)).start()