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

你。 提交于 2019-11-27 04:07:19

问题


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?


回答1:


There is no way for a thread to autonomously gain access to its own std::thread. This is on purpose since std::thread is a move-only type.

I believe what you're requesting is a native_handle() member of std::thread::id, and that is an interesting suggestion. 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.

One way to try to change the C++ standard is to submit issues. Here are directions on how to do so.




回答2:


C++11 does not provide a mechanism for getting the current threads native_handle. You must use platform specific calls, i.e. GetCurrentThread() on Windows:

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



回答3:


As Howard pointed, there is no support for this in ISO C++ yet.

But thread::id has an overloaded operator<< to print itself to an 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.



来源:https://stackoverflow.com/questions/16259257/c11-native-handle-is-not-a-member-of-stdthis-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!