[Pythonmac-SIG] Python threading.Thread vs PyObjC performOnMainThread

gandreas@gandreas.com gandreas at gandreas.com
Mon May 16 21:28:54 CEST 2005


On May 16, 2005, at 2:12 PM, Ronald Oussoren wrote:

>
> On 16-mei-2005, at 20:53, gandreas at gandreas.com wrote:
>
>>>
>>> NO!  That is really really horribly bad to do.  Working around a
>>> bug in PyObjC by writing code that will break in correct versions
>>> of PyObjC is absolutely horrible.  You should NEVER release the
>>> lock unless you own it.
>>>
>>>
>>>
>>
>> Here, then, is probably the heart of the problem - the interactions
>> between python threads spawned by threading.Thread and the main
>> (objc) thread and performSelectorOnMainThread are "undefined", and
>> the more I look at it, the more it appears that using
>> threading.Thread in a PyObjC app is a bad idea and should probably
>> just be chalked up as "unsupported and probably won't work".  It
>> appears that I'd need to build something on top of NSThread (in
>> Objective-C) with explicit thread state handling to get this to work
>> consistently and correctly.
>>
>
> Threading.Thread should work as long as Cocoa knows that the  
> application is
> multithreaded or you don't call Cocoa outside of the main thread. (See
> http://developer.apple.com/documentation/Cocoa/Conceptual/ 
> Multithreading/index.html#//apple_ref/doc/uid/10000057i,
> threading.Thread uses POSIX threads)
>

The  problem isn't the Cocoa threads (Cocoa knows that the  
application is multithreaded).  The problem is that the python code  
that is executing in a threading.Thread calls  
performSelectorOnMainThread to do the UI on the main thread (which,  
since waits for that to complete, blocking the interpreter).  The  
selector called in turn tries to interpret additional Python code,  
but can't because the lock is held by the blocked threading.Thread  
and a simple case of deadlock occurs.

If something from threading.Thread calls a "pure" Objective-C routine  
via performSelectorOnMainThread there is no problem (as far as I've  
seen so far) - it's only when that routine wants to execute  
additional python code that there is a problem.

Glenn Andreas                      gandreas at gandreas.com
  <http://www.gandreas.com/> oh my!
quadrium | build, mutate, evolve | images, textures, backgrounds, art



More information about the Pythonmac-SIG mailing list