06 May 10
23:01

Cocoa and pthreads

結論から言う。
If you’re building a cocoa app, don’t use pthread mutexes and pthread threads.  Use NSThread and NSLock.  I’ve written a few cocoa apps that use pthreads, but maybe I’ve just been lucky till now.

I just spent about 8 work hours trying to figure out why my NSTextStorage object wouldn’t concatenate properly with my NSMutableAttributed, occasionally crashing the NSTextView. A lot of google searches pointed to memory stomping so I debugged with both GuardMalloc and NSZombieEnabled and set breakpoints on my raiseException methods. No beans.

Then I saw that maybe I should be surrounding my appendAttributedString calls to NSMutableAttributedString (and NSTextStorage) with -[NSMutableAttributedString beginEditing] and -[NSMutableAttributedString endEditing].  Did this.  Same result.

I was updating the text in my NSTextView from the consumer main thread by popping off strings from a worker producer thread.  I was doing this in a thread-way using pthread threads and pthread mutexes to make sure the shared objects were handled safely.  Then I noticed a mailing list post and Apple doc that says you need to create at least one NSThread before autoreleasing works correctly.  So I changed my pthread threads to NSThread threads, which are just pthreads that have a bit more on top.  Things still didn’t work.  Lastly out of desperation I changed my pthread mutexes to NSLocks.  Then everything worked.  It looks like somehow the pthread mutexes were slipping.  I don’t know why, but for now I’ve stopped the bleeding.


CAPTCHA Image
*