views:

440

answers:

3

I am developing a multi-threaded application in Cocoa. The main thread takes values from the user, and when a button is clicked I invoke a secondary thread in which a long calculation takes place. Now from this thread I have to return the output of every step of the calculation to the main thread. I want to periodically send data from one thread to the other. I can't find any simple example that does this. Any ideas?

A: 

Have a look at the Apple docs for this.

You may need to create an ADC member account, but this is free

Multi-threaded Cocoa Programs

Abizern
+4  A: 

There are a number of ways to do this, in rough order of complexity (easiest first):

  • use NSObject's performSelectorOnMainThread:withObject:waitUntilDone: which is pretty self explanatory.
  • use performSelector:onThread:withObject:waitUntilDone:, which will let you go the other way
  • use an NSNotification (and NSDistributedNotificationCenter), though you can easily run into a race condition if you're not careful
  • Use NSPorts to send data back and forth

Check out the doc that Abizer mentioned for details on all of these.

Ben Gottlieb
Thanks Ben - I was being lazy.
Abizern
NSNotifcation's are sent on the thread they are posted, so that doesn't really help. Distributed notifications can be used between thread, though.
Dave Dribin
Ah, good catch, thanks Dave!
Ben Gottlieb
+1  A: 

performSelectorOnMainThread:withObject:waitUntilDone: is often the easiest way to update the UI with a background thread's progress. You could also create your own storage area that's safe to access between threads using NSLock or a similar mechanism, or even use distributed objects (which also works between processes or over a network).

Then there's NSOperationQueue and NSOperation which does help a lot to simplify multi-threaded programming, although a lot of programmers have been avoiding it since it can cause a crash in certain circumstances under Leopard.

Marc Charbonneau