20100127

NSThread

The project I'm working on uses threads. Like a good Cocoa app, the main thread is in charge of the GUI, and the worker threads run in the background so that we don't pinwheel.
In order to know when the thread has finished its work, we registered for notification:

[[NSNotificationCenter defaultCenter] addObserver:self
selector:aSel
name:NSThreadWillExitNotification
object:thread];


and in the aSel method, use ivars to update an NSTableView's dataSource.

We had a really pesky race condition that, after two days, we realized was caused by aSel running in the same worker thread! It turns out that this is in the documentation, that notifications are served to the same thread that posts them. However, this is a fairly useless implementation decision.

Our workaround is not to register for the notification, but rather to have the thread performSelectorOnMainThread:withObject:waitUntilDone: at the end of its execution. There is still a problem that we'd like to release the thread at that point, but we don't know what will happen if we try that!

No comments:

Post a Comment