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?
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.
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.
When thread::join() returns, the OS thread of execution has completed and the C++ thread object can be destroyed.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With