Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create std::thread from native handle?

Tags:

c++

c++11

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?

like image 592
KnowItAllWannabe Avatar asked Nov 13 '12 00:11

KnowItAllWannabe


1 Answers

With GCC you can construct a std::thread::id from a std::thread::native_handle_type but you cannot construct a std::thread from it.

This means you can test whether a given pthread_t refers to the same thread as a std::thread object (or to this_thread::get_id()) but you cannot create new thread objects from it.

A std::thread is designed to be a unique handle to a thread. The only way for a different thread object 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:

// start new thread
std::thread t(&thread_func);

// now have two handles to the same thread
std::thread t2( t.native_handle() );

std::thread t1.join();

// erm, hang on, this isn't right
std::thread t2.join();

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).

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" thread objects... but at least GCC doesn't support doing that.

like image 128
Jonathan Wakely Avatar answered Oct 14 '22 14:10

Jonathan Wakely