测试 std::thread 本机句柄实现

Test for std::thread native handle implementation

使用 std::thread::native_handle(),我可以在我的实现中获取底层 pthreads 句柄(mingw-w64 with pthreads)

但是有没有办法在预处理期间检查实现是否实际上使用了本机 pthreads 或其他东西(win32 线程等...)? 我想使代码尽可能可移植,它将使用本机句柄来设置线程优先级。如果在编译期间不支持实现,这将在编译时被禁用。

但最重要的是,我想在构建配置或编译期间防止以下情况:autoconf 检测到 pthreads,但实现不使用 pthreads 而是其他东西,我将错误的句柄传递给 pthreads。

简介

没有什么可以说某个 MACRO 或等价物可用于预处理器(这将产生某个实现正在使用的线程实现)。


如果我们改为检查 std::thread::native_handler (std::thread::native_handle_type) 的 returned 值(更具体地说是 returned 类型),人们可能会认为它会产生更好的结果。

除了对我们没有帮助之外,问题在于所述函数的 return 类型是 实现定义的 ;这意味着它可以 return 任何东西,只要它恰好是可以用作底层线程实现句柄的东西。

更糟的是;该功能可能根本不存在,如 [thread.req.native]:

中所述

30.2.3/1 Native handles [thread.req.native]p1

Several classes described in this Clause have members native_handle_type and native_handle. The presence of these members and their semantics is implementation-defined.



详细说明

查看与pthreads关联的句柄,发现是pthread_t——这个type-id最多对于内在类型 unsigned long int.

通常是 typedef

如果我们深入研究 win32 线程库,我们会发现使用的句柄是 HANDLE 类型,(经过更多挖掘)最终是 void *.


即使我们可以实现地假设 pthread_t "always" 是整数类型,并且 HANDLE "always" 归结为 pointer-to-void;没有这样的保证。

如果另一个线程实现也将 unsigned longvoid* 作为其线程句柄怎么办?我们如何将它与前两个区分开来?

总结一下;人们不应该仅仅依赖 std::thread::native_handler 中的 returned 类型来查询底层线程实现,因为没有人说它将是唯一类型(跨不同的线程实现)。



建议

编写软件时不要依赖底层线程实现,只需使用 std::thread 并完成它即可。

如果 <thread> 中没有您“必须”拥有的某些功能,您将不得不依赖一些外部魔法(例如 autoconf).