Create std :: thread from inline descriptor?

If I have a std::thread t object, I can use t.native_handle() to access the core thread implementation API (like pthreads or Windows threads). But what if I have a handle from the base thread implementation (e.g. pthreads thread). Is there a way to convert this to C ++ 11 std::thread ?

The motivation for this is that it would be advisable to use the streaming platform API to configure the stream, for example, with a certain affinity or a specific stack size (or some other feature not available through the C + +11 API). However, from this point of view, it would be nice to stick with C ++ 11 functionality.

Is there any way to do this?

+4
source share
1 answer

With GCC, you can build std::thread::id from std::thread::native_handle_type , but you cannot build std::thread from it.

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

A std::thread is for creating a unique std::thread handle. The only way for another thread to take control of the main thread is to move it from the original, so that only one object "owns" it at once. If you can create them from the built-in descriptor, you can 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 would be advisable to use the streaming platform API to configure the stream, for example, with a certain affinity or a specific stack size (or some other feature not available through the C + +11 API).

Ideally, the platform will allow you to specify parameters such as affinity or stacking when you create a stream, which allows you to use these functions for a specific platform without loosening the type system, creating non-owning thread objects ... but at least GCC does not support this.

+6
source

Source: https://habr.com/ru/post/1445656/


All Articles