Reputation: 35984
I have seen the following implementation from
c++ concurrency in action
The design of scoped_thread
is to have it actually take ownership of the thread.
class scoped_thread
{
std::thread t;
public:
explicit scoped_thread( std::thread t_ ) :
t( std::move( t_ ) )
{
if ( !t.joinable() )
throw std::logic_error( "thread is not joinable" );
}
~scoped_thread()
{
t.join();
}
scoped_thread( scoped_thread const& ) = delete;
scoped_thread& operator=( scoped_thread const& ) = delete;
};
Usage example:
struct func;
void f()
{
int some_local_state;
scoped_thread t(std::thread(func(some_local_state)));
do_something_in_current_thread();
}
What will happen if the caller uses the following code instead?
struct func;
void f()
{
int some_local_state;
std::thread t1(func(some_local_state));
scoped_thread t(t1); // pass by value
do_something_in_current_thread();
}
The concern I have is that the pass by value
will cause the scoped_thread not owns the thread t1.
Can someone clarify for me?
Upvotes: 0
Views: 233
Reputation: 171263
scoped_thread t(t1); // pass by value
That won't compile, because std::thread
is not copyable (because it has a move constructor, but not a copy constructor).
The only way to construct a scoped_thread
from an existing std::thread
is by moving it, which transfers ownership:
scoped_thread t(std::move(t1));
So you don't need to be concerned.
Upvotes: 4