dimanche 7 janvier 2018

Returning thread-local data from a shared library C-api

Is it safe and portable to return a pointer to a thread_local data from a shared library providing a traditional C-API? The lib itself is naturally implemented with C++11. Safetyness in respect to memory leaks and race conditions, portablitity covering the main desktop OSs: Windows, Linux and OSX. The calling application might be for example native, java, C# etc.

The use case is to implement caller-friendly and thread-safe routine which returns data from shared library. In this case consequent calls specifically will overwrite the thread-local buffer, and this drawback is preferred over requiring the caller to explicitely free the returned data using a library provided "free_data()" function.

// Example 1) As a return value:
const char* text = MYLIB_get_foo_info();

// Example 2) As an output parameter:
const char* result = 0;
MYLIB_foo(&result);

Is it quaranteed that when the library user (application) thread terminate the TLS memory is deallocated at that moment? For example if the returned string is static thread_local std::string in the library.

Already did some searching but failed to find clear and direct answer this specific case (of using TLS from a shared library). Found two good articles about library API design, but these do not give any hints regarding TLS: http://ift.tt/1cZ7xah http://ift.tt/2F9SqwC

Before C++11 for example with Windows one could use TlsAlloc() but one had to specifically check for library-caller threads created before loading the lib. Am I correct that with C++11 thread_local one does not have this kind of issues anymore? http://ift.tt/2EjuMwb

All wisdom related to the issue would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire