在 thrd_t 上调用 pthread 函数是否合法?

Is it legal to call pthread functions on thrd_t?

C11 对线程的支持很好,但并不详尽。如果我需要使用 pthread 函数,我想了解将 thrd_t 转换为 pthread_t 是否合法。例如:

#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提供了std::thread::native_handle获取pthread函数中的pthread_t值,但是C11没有提供这样的功能。由于 thrd_tpthread_t 都是 unsigned long int 的类型定义,我想它们是兼容的。标准对此有何规定?


编辑:同样的问题也适用于threads.h提供的其他两种类型,即mtx_tcnd_t

这是无效的 - 它们有不同的界面,并且可能会在您不知情的情况下发生变化。

即使 thrd_tthread_t 恰好具有相同的别名,但不一定在所有平台上都是如此,更重要的是,它们不一定具有相同的别名 表示线程的数据结构。

实际上,这可能适用于 Linux,因为大多数 C11 和 C++11 线程实现都构建在 pthreads 库之上。但即使在 Linux 上,也不能保证将来会相同(例如,您的系统可能使用提供自己的线程实现的不同 C 库)。

我建议您使用 C11 或 pthreads,但不要假定存在任何互操作性,无论它现在是否工作。如果将来的 C 标准提供此类保证,这当然会改变。但目前还没有。