I'm having some problems with apparently getting wrong results from pthread_getspecific
in a library that's designed to link into various iOS apps.
I see that Apple writes:
Cocoa and POSIX store the thread dictionary in different ways, so you cannot mix and match calls to the two technologies. As long as you stick with one technology inside your thread code, however, the end results should be similar. In Cocoa, you use the threadDictionary method of an NSThread object to retrieve an NSMutableDictionary object, to which you can add any keys required by your thread. In POSIX, you use the pthread_setspecific and pthread_getspecific functions to set and get the keys and values of your thread.
Does that mean that neither the Cocoa nor POSIX TLS functions can be expected to work in library code when we don't know whether the code that calls us is already using one or the other?
How does one get to store and retrieve a thread-local pointer robustly in these circumstances?
Is there a native Darwin TLS support API we should be using instead of either Cocoa or POSIX?
I believe the point that Apple's docs are making is that you cannot use pthread_setspecific
to set a value and then expect it to be available in threadDictionary
. I wouldn't expect them to directly interfere with each other; they're just separate.
That said, if this is iOS-specific code, then the strongly preferred way to manage this is with GCD rather than POSIX threads. GCD offers the equivalent of TLS in the form of dispatch_get_specific
, dispatch_queue_get_specific
and dispatch_queue_set_specific
. But it also provides much better thread management than POSIX threads.
If you don't mind using C++, boost has thread_specific_ptr
. It supports iOS. If you don't want to use C++, the implementation probably offers some hints on how to make it work without a lot of external dependencies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With