python线程块 [英] python threading blocks

查看:40
本文介绍了python线程块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a program which creates new threads in a loop, and doesn't wait for them to finish. As i understand it if i use .start() on the thread, my main loop should just continue, and the other thread will go off and do its work at the same time

但是一旦我的新线程开始,循环就会阻塞,直到线程完成.我是否误解了线程在 python 中的工作原理,或者我正在做一些愚蠢的事情.

However once my new thread starts, the loop blocks until the thread completes. Have I misunderstood how threading works in python, or is there something stupid I'm doing.

这是我创建新线程的代码.

here is my code for creating new threads.

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'

谢谢大家

推荐答案

这会调用函数并将其结果作为 target 传递:

This calls the function and passes its result as target:

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

去掉括号以传递函数对象本身:

Lose the parentheses to pass the function object itself:

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

这篇关于python线程块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆