4

How I can pass message between 2 threads? For example I have NSThread A and NSThread B and I need to pass message from Thread A to Thread B.

How I can check if Thread A is active or completed? and if active then how i can pass message to it.

Any help will be appreciated.

Kamleshwar
  • 2,967
  • 1
  • 25
  • 27
  • 2
    It is not recommended to use NSThreads by the way. I would read Apple's concurrency programming guide: https://developer.apple.com/library/ios/DOCUMENTATION/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html – mattyohe Sep 02 '13 at 19:41
  • 1
    Specifically read the "Migrating Away from Threads" section: https://developer.apple.com/library/ios/DOCUMENTATION/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html. As mattyohe says, using raw `NSThread` objects is not recommended. Dispatch queues and operation queues are the recommended approaches. – Rob Napier Sep 02 '13 at 19:51
  • 1
    “How I can check if Thread A is active or completed? and if active then how i can pass message to it.” This is an example of a race condition. Suppose you find that Thread A is active, *and then it completes before you send your message to it*. Then you send your message to a completed thread. Now what? The correct way is try *unconditionally* to send it, and respond appropriately if the attempt fails. – Peter Hosey Sep 03 '13 at 02:07

2 Answers2

2

There are multiple ways to do this, both roll-your-own and provided by the system. Start with Inter-thread Communication in the Thread Programming Guide

CRD
  • 52,522
  • 5
  • 70
  • 86
  • 5
    Be sure to start at the Introduction, which notes: "Important: If you are developing a new application, you are encouraged to investigate the alternative OS X technologies for implementing concurrency." – Rob Napier Sep 02 '13 at 19:53
  • 1
    And to provide a little balance to all the "avoid threads" comments, from @RobNapier's reference above: "moving away from threads may not be possible in all cases". Maybe you can migrate from threads, maybe not - and a particular collection of cooperating independent concurrent agents maybe one of those cases. – CRD Sep 02 '13 at 20:17
0

You pass messages between threads with shared memory. I'm not sure if NSThread has any message passing capabilities. But mainly you would share memory by using global variables. You could also pass a message through a shared instance of an object.

You should research using locks etc.

drfear
  • 121
  • 1
  • 7