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.
How to get a "parent" thread for NSThread in iOS?
-
31-07-2022 - |
質問
Assuming the "parent" thread is not the main thread. How can I know from the thread what thread has triggered its creation?
Example:
- Main thread triggers creation of ThreadA
- ThreadA triggers creation of ThreadB
- 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.
解決
他のヒント
Can you just give the "currentThread" as an argument when you "detachNewThreadSelector:toTarget:withObject:" ?
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.