简体   繁体   English

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

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

In the following code snippet,在下面的代码片段中,

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

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

  t1.join();
  return 0;
}

How do you get the native_handle from std::this_thread from within the function foo ?您如何从函数foo std::this_thread获取native_handle

There is no way for a thread to autonomously gain access to its own std::thread .线程无法自主访问其自己的std::thread This is on purpose since std::thread is a move-only type.这是故意的,因为std::thread是仅移动类型。

I believe what you're requesting is a native_handle() member of std::thread::id , and that is an interesting suggestion.我相信您要求的是std::thread::idnative_handle()成员,这是一个有趣的建议。 As far as I know it is not currently possible.据我所知,目前是不可能的。 It would be used like:它会像这样使用:

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

It wouldn't be guaranteed to work, or even exist.它不能保证工作,甚至不存在。 However I imagine most POSIX platforms could support it.但是我想大多数 POSIX 平台都可以支持它。

One way to try to change the C++ standard is to submit issues.尝试更改 C++ 标准的一种方法是提交问题。 Here are directions on how to do so. 以下是有关如何执行此操作的说明。

C++11 does not provide a mechanism for getting the current threads native_handle. C++11 没有提供获取当前线程 native_handle 的机制。 You must use platform specific calls, ie GetCurrentThread() on Windows:您必须使用特定于平台的调用,即 Windows 上的 GetCurrentThread():

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

As Howard pointed, there is no support for this in ISO C++ yet.正如霍华德指出的那样,ISO C++ 尚不支持此功能。

But thread::id has an overloadedoperator<< to print itself to an ostream .但是thread::id有一个重载的operator<<将自己打印ostream

#include <iostream>
#include <thread>

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

Without knowing the semantics of the actual value (which is highly platform-dependent), printing it or using it as a key in a map is the most you should be doing anyway.在不知道实际值的语义(高度依赖于平台)的情况下,打印它或将其用作地图中的键是您最应该做的。

Currently(C++17) you can't get native_handle from std::this_thread当前(C++17)你不能从std::this_thread得到native_handle

The most possible interface might be std::this_thread::native_handle() .最可能的接口可能是std::this_thread::native_handle() But not std::this_thread::get_id().native_handle();但不是std::this_thread::get_id().native_handle(); by @Howard通过@霍华德

Since Win/Linux/MacOS implement thread and thread::id differently: (below is informal pseudo code)由于 Win/Linux/MacOS 对threadthread::id不同:(以下是非正式的伪代码)

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

As you can see only in Linux source there is native_hanlde object implemented in thread::id structure.正如您只能在 Linux 源代码中看到的,在thread::id结构中实现了native_hanlde对象。 Thus on Win/MacOS you can't get the native_handle from an id object.因此,在 Win/MacOS 上,您无法从id对象获取native_handle

Finally, if your code runs only in Linux, there is a dirty trick to get native_handle from this_thread which I will never recommend:最后,如果您的代码仅在 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);

In fact, there is one funny way to circumvent the problem and access it via std::thread , which may work in some cases.事实上,有一种有趣的方法可以绕过这个问题并通过 std::thread 访问它,这在某些情况下可能有效。 The original example was posted on this blog .原始示例发布在此博客上 I rewritten it.我重写了它。 You can save the code below to test.cpp and compile & run it :您可以将下面的代码保存到 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.

相关问题 使用C ++ 11 std :: thread native_handle以及我是否需要CloseHandle - Using C++11 std::thread native_handle and whether I need to CloseHandle C++11 线程等待行为:std::this_thread::yield() 与 std::this_thread::sleep_for( std::chrono::milliseconds(1) ) - C++11 Thread waiting behaviour: std::this_thread::yield() vs. std::this_thread::sleep_for( std::chrono::milliseconds(1) ) C ++ 11 std :: this_thread - 如何取消sleep_until()? - C++11 std::this_thread - How to cancel sleep_until ()? 使用native_handle()+ pthread_cancel()取消std :: thread - cancelling std::thread using native_handle() + pthread_cancel() 是否为C ++ 11中的信号中断(或信号处理程序)定义了std :: this_thread :: sleep_for行为? - Is std::this_thread::sleep_for behaviour defined for signal interupt ( or signal handler) in C++11? 使用GCC 4.8.5编译时,C ++ 11 std :: this_thread :: sleep_until()挂起 - C++11 std::this_thread::sleep_until() hangs when compiled with GCC 4.8.5 'yield'不是'std :: this_thread'的成员 - 'yield' is not a member of 'std::this_thread' C ++ 11:错误:'begin'不是'std'的成员 - C++11 : error: ‘begin’ is not a member of ‘std’ 来自c ++ 11的std :: thread问题 - Issue with std::thread from c++11 C ++ 11线程修改std :: list - C++11 thread to modify std::list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM