Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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()

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.

like image 873
dperrie Avatar asked Jan 10 '17 09:01

dperrie


1 Answers

Problem is that you're actually calling your method when passing it as argument of 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()

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

like image 123
Jean-François Fabre Avatar answered Sep 25 '22 20:09

Jean-François Fabre