Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++11, what is the point of a thread which "does not represent a thread of execution"?

Looking over the new threading stuff in C++11 to see how easily it maps to pthreads, I notice the curious section in the thread constructor area:

thread();
Effects: Constructs a thread object that does not represent a thread of execution.
Postcondition: get_id() == id()
Throws: Nothing.

In other words, the default constructor for a thread doesn't actually seem to create a thread. Obviously, it creates a thread object, but how exactly is that useful if there's no backing code for it? Is there some other way that a "thread of execution" can be attached to that object, like thrd.start() or something similar?

like image 670
paxdiablo Avatar asked Sep 26 '11 03:09

paxdiablo


People also ask

What happens if a thread is not joined?

If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything.

What is a detached thread?

The pthread_detach() function marks the thread identified by thread as detached. When a detached thread terminates, its resources are automatically released back to the system without the need for another thread to join with the terminated thread.

Does join destroy a thread C++?

When thread::join() returns, the OS thread of execution has completed and the C++ thread object can be destroyed.

How do you join a detached thread?

If a thread is created as detached, it can never be joined. The final draft of the POSIX standard specifies that threads should be created as joinable. To explicitly create a thread as joinable or detached, the attr argument in the pthread_create() routine is used.


1 Answers

Is there some other way that a "thread of execution" can be attached to that object, like thrd.start() or something similar?

// deferred start std::thread thread;  // ...  // let's start now thread = std::thread(functor, arg0, arg1); 

std::thread is a MoveConstructible and MoveAssignable type. So that means that in code like std::thread zombie(some_functor); std::thread steal(std::move(zombie)); zombie will be left in a special, but valid, state associated with no thread of execution. The default constructor comes free in a sense since all it has to do is put the object into that exact state. It also allows arrays of std::thread and operations like std::vector<std::thread>::resize.

like image 70
Luc Danton Avatar answered Sep 21 '22 01:09

Luc Danton