繁体   English   中英

C++11“native_handle”不是“std::this_thread”的成员

[英]C++11 'native_handle' is not a member of 'std::this_thread'

在下面的代码片段中,

void foo() {
  std::this_thread::native_handle().... //error here
}

int main() {
  std::thread t1(foo);

  t1.join();
  return 0;
}

您如何从函数foo std::this_thread获取native_handle

线程无法自主访问其自己的std::thread 这是故意的,因为std::thread是仅移动类型。

我相信您要求的是std::thread::idnative_handle()成员,这是一个有趣的建议。 据我所知,目前是不可能的。 它会像这样使用:

void foo()
{
    auto native_me = std::this_thread::get_id().native_handle();
    // ...
}

它不能保证工作,甚至不存在。 但是我想大多数 POSIX 平台都可以支持它。

尝试更改 C++ 标准的一种方法是提交问题。 以下是有关如何执行此操作的说明。

C++11 没有提供获取当前线程 native_handle 的机制。 您必须使用特定于平台的调用,即 Windows 上的 GetCurrentThread():

void foo()
{
    auto native_me = ::GetCurrentThread();
}

正如霍华德指出的那样,ISO C++ 尚不支持此功能。

但是thread::id有一个重载的operator<<将自己打印ostream

#include <iostream>
#include <thread>

int main()
{
    std::cout << "Current thread ID: " << std::this_thread::get_id() << std::endl;
}

在不知道实际值的语义(高度依赖于平台)的情况下,打印它或将其用作地图中的键是您最应该做的。

当前(C++17)你不能从std::this_thread得到native_handle

最可能的接口可能是std::this_thread::native_handle() 但不是std::this_thread::get_id().native_handle(); 通过@霍华德

由于 Win/Linux/MacOS 对threadthread::id不同:(以下是非正式的伪代码)

  • 在 Linux 上native_handle存储在线程中。 _M_id(id 类型) ._M_thread。
  • 在 Windows 上, native_handle存储在 thread._Thr(类型 _Thrd_t,而不是类型 id)。_Hnd。
  • 在 MacOS 上, native_handle存储在 thread.__t_ 处。

正如您只能在 Linux 源代码中看到的,在thread::id结构中实现了native_hanlde对象。 因此,在 Win/MacOS 上,您无法从id对象获取native_handle

最后,如果您的代码仅在 Linux 中运行,那么从this_thread获取native_handle有一个肮脏的技巧,我永远不会推荐:

auto thread_id = std::this_thread::get_id();
auto native_handle = *reinterpret_cast<std::thread::native_handle_type*>(&thread_id);

事实上,有一种有趣的方法可以绕过这个问题并通过 std::thread 访问它,这在某些情况下可能有效。 原始示例发布在此博客上 我重写了它。 您可以将下面的代码保存到 test.cpp 并编译并运行它:

// g++ ./test.cpp  -lpthread && ./a.out
// 
#include <thread>
#include <vector>
#include <iostream>
#include <mutex>
#include <sched.h>
#include <pthread.h>
int main(int argc, const char** argv) {
  constexpr unsigned num_threads = 4;
  // A mutex ensures orderly access to std::cout from multiple threads.
  std::mutex iomutex;
  std::vector<std::thread> threads(num_threads);
  for (unsigned i = 0; i < num_threads; ++i) {
    threads[i] = std::thread([&iomutex, i,&threads] {
      // Create a cpu_set_t object representing a set of CPUs. Clear it and mark
      // only CPU i as set.
      cpu_set_t cpuset;
      CPU_ZERO(&cpuset);
      CPU_SET(i, &cpuset);
      int rc = pthread_setaffinity_np(threads[i].native_handle(),
                                      sizeof(cpu_set_t), &cpuset);
      if (rc != 0) {
        std::cerr << "Error calling pthread_setaffinity_np: " << rc << "\n";
      }
      std::this_thread::sleep_for(std::chrono::milliseconds(20));
      while (1) {
        {
          // Use a lexical scope and lock_guard to safely lock the mutex only
          // for the duration of std::cout usage.
          std::lock_guard<std::mutex> iolock(iomutex);
          std::cout << "Thread #" << i << ": on CPU " << sched_getcpu() << "\n";
        }

        // Simulate important work done by the tread by sleeping for a bit...
        std::this_thread::sleep_for(std::chrono::milliseconds(900));
      }
    });


  }

  for (auto& t : threads) {
    t.join();
  }
  return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM