Reputation: 9292
With std::thread::native_handle()
, I can get the underlying pthreads handle in my implementation (mingw-w64 with pthreads)
But is there a way to check during preprocessing if the implementation is actually using native pthreads or something else (win32 threads, etc...) ? I would like to make a code as portable as possible, which would use the native handle for setting the thread priority. This would be disabled at compile time if the implementation is not supported during compilation.
But most importantly, I would like to prevent the following case during build configuration or compilation : pthreads is detected by autoconf, but the implementation does not use pthreads but something else, and I pass a wrong handle to pthreads.
Upvotes: 0
Views: 681
Reputation: 63832
There's nothing saying that a certain MACRO, or equivalent, will be available for the preprocessor (that would yield what thread-implementation a certain implementation is using).
If we instead were to inspect the returned value (more specifically the returned type) of std::thread::native_handler
(std::thread::native_handle_type
) one might think that it would yield a better result.
The problem, beyond the fact that it won't help us, is that the return-type of said function is implementation-defined; meaning that it could return anything, as long as that happens to be something that can be used as a handle for the underlying thread implementation.
And even worse; the function might not be present at all, as described in [thread.req.native]:
30.2.3/1 Native handles
[thread.req.native]p1
Several classes described in this Clause have members
native_handle_type
andnative_handle
. The presence of these members and their semantics is implementation-defined.
Looking at the handle associated with pthreads, we find that it is pthread_t
- this type-id is most often a typedef for the intrinsic type unsigned long int
.
If we dive into the win32 threading library we see that the handle used is of type HANDLE
, which (after some more digging) ends up being void *
.
Even if we could, realizably, assume that pthread_t "always" is an integral type, and that HANDLE
"always" boils down to being a pointer-to-void; there's no such guarantee.
What if another threading implementation also has unsigned long
or void*
as its thread handle; how would we distinguish that from the previous two?
To sum it up; one should not rely on the returned type from std::thread::native_handler
to query the underlying thread implementation simply because there's nothing saying that it will be a unique type (across different threading implementations).
Don't rely on the underlying thread implementation when writing your software, simply use std::thread
and work through that.
If there is some functionality that isn't present in <thread>
that you "must" have, you will have to rely on some external magic (such as autoconf).
Upvotes: 1