How to get std::thread of current thread?

前端 未结 3 400
忘掉有多难
忘掉有多难 2021-01-04 03:58

How can I get a std::thread object representing current (already running thread).

I know I can do std::this_thread::get_id(). However, this

相关标签:
3条回答
  • 2021-01-04 04:28

    std::thread is not copy able. Being able to arbitrarily get a thread without getting the resources from initial creation would break how the thread is supposed to work.

    Any reference to a thread should be or have been moved from the object that the constructor was called on.

    0 讨论(0)
  • 2021-01-04 04:39

    You can't get a std::thread object referring to a thread that wasn't created by the std::thread constructor. Either consistently use the C++ thread library, or don't use it at all. If the current thread was created by pthread_create, for example, it will need to be joined to using pthread_join.

    0 讨论(0)
  • 2021-01-04 04:46

    Assuming your code uses std::thread to start the "other thread", that wants to join() the "current thread"

    If the "current thread" is the main thread, i.e. the one started by main(), you cannot make it a std::thread() instance, for good reasons (e.g. if main thread exits, the entire process exits). You should not have other thread join main thread anyway.

    If the "current thread" is created from your own code, then you should change it to use std::thread.

    If the "current thread" is created from third party library, then you should use the same threading implementation as exposed by third party library. Normally if the third party library expects you to "join()" their thread, they would have exposed a join() method to you, or indicate that you should use specific thread implementation API (e.g. POSIX thread) to join.

    Either way, it seems that for good reasons, you cannot do what you wanted.

    0 讨论(0)
提交回复
热议问题