How to make reliable local data storage in iOS

I am having some problems with the appearance of incorrect pthread_getspecific results in a library that is designed to communicate in various iOS applications.

I see that Apple writes :

Cocoa and POSIX store the thread dictionary differently, so you cannot mix and match calls with the two technologies. However, if you stick to the same technology inside your stream code, 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 needed for your thread. On POSIX, you use the special functions pthread_setspecific and pthread_gets to set and retrieve the keys and values ​​of your thread.

Does this mean that you can’t expect that the Cocoa and POSIX TLS functions will work in the library code if we don’t know if the code that calls us uses this or that?

How can I get reliable storage and a local stream pointer in these circumstances?

Is there a native Darwin TLS support API that we should use instead of Cocoa or POSIX?

+6
source share
2 answers

I believe Apple's business docs are that you cannot use pthread_setspecific to set a value, and then expect it to be available in threadDictionary . I did not expect that they would directly interfere with each other; they are simply divided.

However, if this is iOS-specific code, a strongly preferred way is to control it using GCD rather than POSIX streams. 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 flow control than POSIX streams.

+6
source

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 tips on how to make it work without a lot of external dependencies.

+1
source

Source: https://habr.com/ru/post/951133/


All Articles