[Twisted-Python] test if thread is reactor's thread

Jamu Kakar jkakar at kakar.ca
Wed May 11 15:41:49 EDT 2011


Hi Alessandro,

On Wed, May 11, 2011 at 8:18 PM, Alessandro Dentella <sandro at e-den.it> wrote:
> is there a way to test if the thread a function is called is the reactor's
> thread?

Yes, you can do it with code like this:

from threading import currentThread

if currentThread().getName() == 'MainThread':
    # Code is running in the main reactor thread
else:
    # Code is running in a child thread

> I have a function that can be called from the main thread or from the
> reactor's thread and should behave differently...

We had a situation like this recently in Fluidinfo.  We started with
the trick above, but it was a bit weird.  The situation we had was
that we had to run some asynchronous code (ie, a function returning a
Deferred) in a thread used to run a database transaction.  We ended up
with a nice solution.  Something like:

# In the transaction thread.
proxy = doAThing()
result = blockingCallFromThread(proxy.run)

At first, deep inside doAThing we had the black magic above, but it
was awkward to test and behaved differently depending on which thread
the code ran in, which was confusing to understand.  We refactored
doAThing to not run the asynchronous code but to, instead, return a
proxy object with a method that needed to be run asynchronously.  The
proxy was configured with the arguments and such needed for it to run
properly, so the user could just invoke the asynchronous code in the
way that made sense for them.

It's much nicer because the caller of the function gets to decide how
to run the asynchronous code, instead of it being hard-coded deep in
some logic.  Also, the logic is much easier to comprehend because it
only behaves one way.  Anyway, maybe this strategy won't work for you,
but behaves-differently-depending-on-the-thread-you-use is probably a
behaviour you should avoid if possible.

Thanks,
J.



More information about the Twisted-Python mailing list