[Twisted-Python] test if thread is reactor's thread
Hi, is there a way to test if the thread a function is called is the reactor's thread? I have a function that can be called from the main thread or from the reactor's thread and should behave differently... thanks sandro *:-) -- Sandro Dentella *:-) http://www.reteisi.org Soluzioni libere per le scuole http://sqlkit.argolinux.org SQLkit home page - PyGTK/python/sqlalchemy
Hi Alessandro, On Wed, May 11, 2011 at 8:18 PM, Alessandro Dentella <sandro@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.
Le 11/05/2011 20:18, Alessandro Dentella a écrit :
Hi,
is there a way to test if the thread a function is called is the reactor's thread?
I have a function that can be called from the main thread or from the reactor's thread and should behave differently...
Hi, twisted.python.threadable.isInIOThread() should answer to that question. Regards, -- Thomas
thanks to both of you for the hints. My situation is so simple that i guess a twisted.python.threadable.isInIOThread() should suffice. sandro *:-)
participants (3)
-
Alessandro Dentella
-
Jamu Kakar
-
Thomas Hervé