chriskohlhoff / asio

Asio C++ Library
http://think-async.com/Asio
4.81k stars 1.2k forks source link

Use thread_local when __thread is not available #1272

Closed aladram closed 6 months ago

aladram commented 1 year ago

Due to the current Boost module configuration, the mechanism used to store per-thread variables on Linux with x86 architectures with GCC is keyword __thread. On non-x86 architectures, the code uses a series of pthreads API calls, effectively making per-thread variables inaccessible after they are destroyed. This causes crashes if the call_stack variable present in thread_context is accessed after boost.asio global variables destructors (can happen if server is stopped in atexit handler or global destruction).

While it is always possible to reorder destructors (e.g. __attribute(constructor(<priority>)) on GCC), there is no portable way to achieve this.

This change uses preexisting preprocessor definition BOOST_NO_CXX11_THREAD_LOCAL to determine whether or not keyword thread_local is available, and fallbacks on it in cases where __thread is not available. This is an easy, minimal and portable way to address the aforementioned issue.

Please note that many configurations support __thread. In the future, we could improve the checks to detect these configurations.

aladram commented 1 year ago

@vinipsmaker could you please take a look at this change when you get a chance? Thanks!

aladram commented 1 year ago

@chriskohlhoff if you have the chance to look at this ASAP that would be great, thanks!

aladram commented 5 months ago

Change ba467b95 is an equivalent of this PR, so this can be considered as resolved, thanks!