Last updated:2026-10-12
C++ std::thread Implementation Internals¶
A deep dive into std::thread¶
When we write a lambda and pass it to a thread, when exactly are the thread creation and the task invocation triggered?
This thread is passed a lambda, and the question this section sets out to answer is: when is this lambda invoked? At construction time? Or at some point when it gets called?
Come, let us step into the era of source code.
1. _M_make_routine¶
The code analyzed in this section is, respectively:
1) Header file
https://github.com/gcc-mirror/gcc/blob/releases/gcc-4.9/libstdc%2B%2B-v3/include/std/thread
- Implementation file
https://github.com/gcc-mirror/gcc/blob/releases/gcc-4.9/libstdc%2B%2B-v3/src/c%2B%2B11/thread.cc
- posix header
https://github.com/gcc-mirror/gcc/blob/releases/gcc-4.9/libgcc/gthr-posix.h
The code above will call the following constructor:
template<typename _Callable, typename... _Args>
explicit
thread(_Callable&& __f, _Args&&... __args)
{
_M_start_thread(_M_make_routine(std::__bind_simple(
std::forward<_Callable>(__f),
std::forward<_Args>(__args)...)));
}
__f is the lambda we passed in; here the lambda is bound together with the arguments via bind and then handed to _M_make_routine, which constructs the _Impl.
template<typename _Callable>
shared_ptr<_Impl<_Callable>>
_M_make_routine(_Callable&& __f)
{
// Create and allocate full data structure, not base.
return std::make_shared<_Impl<_Callable>>(std::forward<_Callable>(__f));
}
And what is stored inside _Impl is exactly the result of the bind from before, _M_func.
template<typename _Callable>
struct _Impl : public _Impl_base
{
_Callable _M_func;
_Impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
{ }
void
_M_run() { _M_func(); }
};
Then the shared_ptr<_Impl<_Callable>> created by _M_make_routine is handed over to _M_start_thread.
2. _M_start_thread¶
_M_start_thread calls __gthread_create, and execute_native_thread_routine is passed here.
void
thread::_M_start_thread(__shared_base_type __b)
{
if (!__gthread_active_p())
#if __EXCEPTIONS
throw system_error(make_error_code(errc::operation_not_permitted),
"Enable multithreading to use std::thread");
#else
__throw_system_error(int(errc::operation_not_permitted));
#endif
__b->_M_this_ptr = __b;
int __e = __gthread_create(&_M_id._M_thread,
&execute_native_thread_routine, __b.get());
if (__e)
{
__b->_M_this_ptr.reset();
__throw_system_error(__e);
}
}
Key point 1: execute_native_thread_routine
The code below gives several pieces of information:
First: why extern "C"
Second: _M_run() is called
extern "C"
{
static void*
execute_native_thread_routine(void* __p)
{
thread::_Impl_base* __t = static_cast<thread::_Impl_base*>(__p);
thread::__shared_base_type __local;
__local.swap(__t->_M_this_ptr);
__try
{
__t->_M_run();
}
__catch(const __cxxabiv1::__forced_unwind&)
{
__throw_exception_again;
}
__catch(...)
{
std::terminate();
}
return 0;
}
} // extern "C"
Key point 2: __gthread_create
It calls pthread_create
static inline int
__gthread_create (__gthread_t *__threadid, void *(*__func) (void*),
void *__args)
{
return __gthrw_(pthread_create) (__threadid, NULL, __func, __args);
}
Alright, let us sort out the flow above. When we construct a std::thread, we pass in a custom callback (a lambda) that executes our business logic; the std::thread constructor initiates the pthread_create call and passes execute_native_thread_routine to pthread_create in C style. When pthread_create executes, it runs execute_native_thread_routine, and the _M_run() inside is then invoked — this corresponds to the invocation of our lambda function.
This section has given us a deeper understanding of thread invocation. Did you learn something? Feel free to share.
Related Topics¶
- C++ Concurrency in Action Reading Guide | C++那些事
- C++ Deadlock Troubleshooting | C++那些事
- C++ SIMD Vectorization | C++那些事
- C++17 Parallel STL | C++那些事
- C++ False Sharing and Cache Lines | C++那些事
- GDB Multi-Threaded All-Stop Debugging | C++那些事
- Helgrind Concurrency Error Detection | C++那些事
- libev Event Loop Internals | C++那些事
- C++ std::thread and jthread | C++那些事
- Getting Started with C++ Multithreading | C++那些事