简体   繁体   中英

How to get std::thread of current thread?

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 will give me a std::thread:id object.

My main goal is to allow some other thread to join current one. However, the problem is that current one wasn't started by creation of std::thread, so I couldn't have saved it beforehand.

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 .

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.

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, ie the one started by main(), you cannot make it a std::thread() instance, for good reasons (eg 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 (eg POSIX thread) to join.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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