简体   繁体   English

Python:如何不等待线程完成?

[英]Python: How to NOT wait for a thread to finish to carry on?

So I have some code that waits for X to happen, then creates a thread and does processEmail. 因此,我有一些代码等待X发生,然后创建一个线程并执行processEmail。

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. 我正在寻找的是一种代码,即使processEmail在另一个线程中发生,代码也会继续等待X,但是当前代码只是等待线程完成,然后再等待X再次发生。

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

EDIT: 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. 编辑:仅供参考,我什么都不需要在下面的代码中进一步输出processEmail.main(),因此不需要我等待其输出。

ANSWER Provided by Jean: Remove the () after main. 答案提供者:Jean:取下main之后的()。

Problem is that you're actually calling your method when passing it as argument of Thread . 问题是您实际上在将方法作为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) 这样它就执行了,但是在当前线程中,这就是为什么它可以工作但是被阻塞的原因(并且由于它可能返回None ,所以您从Thread对象中没有得到任何错误,它只是阻塞了)

Remove parentheses to pass the function object, not the result from the call! 删除括号以传递函数对象,而不是调用结果!

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

Note: some IDEs like PyCharm automatically add parentheses to function names. 注意:某些IDE(例如PyCharm)会自动在函数名称中添加括号。 That's a bad idea in that case :) 在这种情况下,这是个坏主意:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM