2

Assuming the "parent" thread is not the main thread. How can I know from the thread what thread has triggered its creation?

Example:

  1. Main thread triggers creation of ThreadA
  2. ThreadA triggers creation of ThreadB
  3. In ThreadB I want to know that ThreadA is it's "parent"

UPD: I am not creating a thread in my app. I am trying to instrument existing applications.

mafonya
  • 2,152
  • 22
  • 21
  • 1
    Did you try to subclass NSThread and add a custom property. Then override the + detachNewThreadSelector:toTarget:withObject: method – Toploulou Nov 19 '13 at 15:50
  • If your need is to communicate with the parent thread, then this question might be useful to you: http://stackoverflow.com/questions/5917772/intra-process-communication-in-objective-c – Monolo Nov 19 '13 at 16:01

3 Answers3

3

You can't. There is no such thing as parent thread. A thread is an independent entity, even if a thread can communicate with other threads but there is no hierarchy involved.

peko
  • 11,267
  • 4
  • 33
  • 48
  • This is the right answer. All the threads are brother threads. There are no parents and children. It took me some time to understand. – mafonya Nov 20 '13 at 07:42
1

Can you just give the "currentThread" as an argument when you "detachNewThreadSelector:toTarget:withObject:" ?

  • I tried to instrument it, but nothing happens. It seems like GCD is not using this specific method when dispatching a queue. It's not obvious what they really use. – mafonya Nov 20 '13 at 07:45
0

As the previous post states you can't directly access the "parent" thread of another thread because a NSThread is independent.

But you can create a mechanism to access the thread that started the current thread, indirectly, using the -threadDictionary or the -name/setName methods.

Basically you can create a custom thread pool that will handle the threads lifecycle and can be accessed from other threads.

But as an observation, I don't see a use of this mechanism. If you really want to run tasks on background and you want to be able to change the lifecycle of the background tasks (cancel/start/etc) you should use NSOperation and NSOperationQueue, this ones will give you all the feature required for a custom thread pool.

danypata
  • 9,895
  • 1
  • 31
  • 44