If I have a std::thread object t, I can use t.native_handle() to get access to the API of the underlying thread implementation (e.g., pthreads or Windows threads). But what if I have a handle from the underlying thread implementation (e.g., a pthreads thread). Is there any way to transform that into a C++11 std::thread?
The motivation for this is that it might be desirable to use the native platform threading API to set up a thread with, e.g., a particular affinity or a particular stack size (or some other characteristic that is not accessible via the C++11 API). From that point forward, however, it’d be nice to stick to the C++11 functionality.
Is there any way to do this?
With GCC you can construct a
std::thread::idfrom astd::thread::native_handle_typebut you cannot construct astd::threadfrom it.This means you can test whether a given
pthread_trefers to the same thread as astd::threadobject (or tothis_thread::get_id()) but you cannot create newthreadobjects from it.A
std::threadis designed to be a unique handle to a thread. The only way for a differentthreadobject to take ownership of the underlying thread is by moving it from the original, so only one object “owns” it at once. If you could construct them from a native handle you could do:Ideally the platform would allow you to specify parameters such as affinity or stacksize when you construct the thread, which would allow you to use those platform-specific features without weakening the type system by constructing “non-owning”
threadobjects… but at least GCC doesn’t support doing that.