Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 911
Victor Ronin Avatar asked Feb 16 '17 00:02

Victor Ronin


People also ask

How do I find my CPP thread ID?

Thread get_id() function in C++ This function returns the value of std::thread::id thus identifying the thread associated with *this. Syntax: thread_name. get_id();

Is std :: thread copyable?

4) The copy constructor is deleted; threads are not copyable. No two std::thread objects may represent the same thread of execution.

Can a thread spawn another thread C++?

A thread does not operate within another thread. They are independent streams of execution within the same process and their coexistence is flat, not hierarchical. Some simple rules to follow when working with multiple threads: Creating threads is expensive, so avoid creating and destroying them rapidly.

What does std :: thread do?

std::thread Threads allow multiple functions to execute concurrently. std::thread objects may also be in the state that does not represent any thread (after default construction, move from, detach, or join), and a thread of execution may not be associated with any thread objects (after detach).


1 Answers

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.

like image 130
Brian Bi Avatar answered Sep 18 '22 15:09

Brian Bi