Python:如何不等待线程完成? [英] Python: How to NOT wait for a thread to finish to carry on?

查看:823
本文介绍了Python:如何不等待线程完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一些代码等待X发生,然后创建一个线程并执行processEmail.

So I have some code that waits for X to happen, then creates a thread and does processEmail.

我正在寻找的是一种代码,即使processEmail在另一个线程中发生,代码也可以继续等待X,但是当前代码只是等待线程完成,然后再等待X再次发生.

What I am looking for is a way for the code to carry on waiting X even though processEmail is happening in another thread but currently the code just waits for the thread to finish before waiting for X to happen again.

if X happens:
    thread = Thread(target = processEmail.main())
    thread.start()

仅供参考,我什么也不需要在下面的代码中输出processEmail.main(),因此不需要我等待它的输出.

FYI I have nothing that requires the output of processEmail.main() further down the code therefore there is no need for me to wait for its output.

Jean提供的答案:移除main之后的().

ANSWER Provided by Jean: Remove the () after main.

推荐答案

问题在于,将方法作为Thread的参数传递时,实际上是在调用方法.

Problem is that you're actually calling your method when passing it as argument of Thread.

它可以执行,但是在当前线程中,这就是为什么它可以工作但被阻塞的原因(并且由于它可能返回None,所以您不会从Thread对象得到任何错误,它只是阻塞了)

So it executes, but in the current thread, that's why it's working but it's blocking (and since it probably returns None, you get no error from the Thread object, it just blocks)

删除括号以传递函数对象,而不是调用结果!

Remove parentheses to pass the function object, not the result from the call!

thread = Thread(target = processEmail.main)
thread.start()

注意:某些IDE(例如PyCharm)会自动在函数名称中添加括号.在这种情况下,这是个坏主意:)

Note: some IDEs like PyCharm automatically add parentheses to function names. That's a bad idea in that case :)

这篇关于Python:如何不等待线程完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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