chriskohlhoff / asio

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

tss_ptr does not play well with fibers that migrate threads #1366

Open bgemmill opened 9 months ago

bgemmill commented 9 months ago

When using boost::fiber with fibers with boost::asio, sometimes we get segfaults because the tss usage inside asio is not fiber-tolerant.

For reference, boost::fiber warns of this, saying "it would be problematic to migrate a fiber that relies on thread-local storage."

The issue is that boost::asio uses tss_ptr a lot while calling detail::thread_context::top_of_thread_call_stack, and this can lead to segfaults.

It looks like a workaround is to force the compiler not to cache the address of the thread_local, effectively always getting the current thread's tss. Stack overflow has a good discussion of it here, where the noinline attribute does the heavy lifting, looking something like:

      __attribute__((noinline))
      static some_data_type& singleton() {
        static thread_local some_data_type tss;
        return tss;
      }

edit: noinline may be the right way to go, I'll test this out locally