[Twisted-Python] twisted threads: synchronous function calls

Markus Schiltknecht markus at bluegap.ch
Tue Jun 20 09:52:28 EDT 2006


I had to use a thread... that thread must also call a function in the 
twisted reactor thread. No problem, I thought, looked up in the fine 
manual and found the reactor.callFromThread(somefunc, someargs...).

Wonderful, so in my separate thread I wrote:

x = reactor.callFromThread(myfunc, myargs...)


callFromThread returns before myfunc finishes. It seems to be useful for 
async function calls, but not for my case.

I ended up writing something like:

def syncCall():

	waitCond = threading.Condition()
	waitCond.result = 0

	def _process(cond):
		cond.result = ..some function call..

	reactor.callFromThread(_process, waitCond)

	return waitCond.result

Now, I might have missed something, but that's sure functionality which 
Twisted should provide.

In my first attempt I let the function return a Defer. I expected the 
reactor to 'send back' the result to the calling thread only after the 
Defer.callback() was called. IMHO that would be the most elegant and 
intuitively way:

def myfunc(myarg):
	Defer d
	reactor.callLater(10, d.callback)
	return d

# from the separate thread one would write:
reactor.callFromThreadSync(myfunc, args)

Am I facing problems I'm not aware of? Did I miss something?



More information about the Twisted-Python mailing list