Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OS X inter thread communication question

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?


2 Answers

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.

like image 68
Ben Gottlieb Avatar answered Dec 15 '25 11:12

Ben Gottlieb


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.

like image 33
Marc Charbonneau Avatar answered Dec 15 '25 12:12

Marc Charbonneau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!