3

The C11 support to thread is fine but not exaustive. In case I need to use pthread functions, I would like to understand if it is legal to cast thrd_t to pthread_t. For example:

#include <threads.h>
#define_GNU_SOURCE
#include <pthread.h>
#include <sched.h>

int main(void) {
    thrd_t t;
    cpu_set_t cpuset;
    // some initialization code here...
    pthread_setaffinity_np((pthread_t)t, sizeof(cpuset), &cpuset) // Is the cast valid?
    // other code here...
}

C++11 provides std::thread::native_handle to get the pthread_t value to be in pthread functions, but C11 does not provide such function. Since, both thrd_t and pthread_t are typedefs to unsigned long int, I suppose they are compatible. What does the standard say about it?


Edit: the same question applies also for the other two types provided by threads.h, i.e. mtx_t and cnd_t.

Giovanni Cerretani
  • 1,693
  • 1
  • 16
  • 30

1 Answers1

3

It's not valid - they have different interfaces and that could change without you knowing.

Even if thrd_t and thread_t happen to have same aliases, that's not necessarily true on all platforms and more so, they don't necessarily have same data structure to represent threads.

In practice, this might work on Linux because most C11 and C++11 thread implementations are built on top of pthreads library. But that's not guaranteed to be the same in the future even on Linux (e.g., your system might use a different C library that provides its own thread implementation).

I'd suggest you use either C11 or pthreads but not assume that there's any interoperability whether or not it works right now. This could change of course if C standard in the future provides such guarantees. But at the moment, it doesn't.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • 1
    Since C11 and C++11 implementation are very similar, actually is not clear why the C versions `thrd_*`, `mtx_*` and `cnd_*` are missing a `*_native_handle` function, provided by all the C++ couterparts. – Giovanni Cerretani Nov 06 '19 at 10:46
  • Even the existing interfaces were not that well specified in C11, [Jen wrote about it](https://gustedt.wordpress.com/2012/10/14/c11-defects-c-threads-are-not-realizable-with-posix-threads/) and there's been [improvements in C17](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2244.htm). But we're just speculating here.. Personally, I'd prefer new interfaces could be wrappers on pthreads) rather than getting a pthread_t and then using pthreads intefaces. – P.P Nov 06 '19 at 10:54