简体   繁体   中英

`scoped_thread` pass by value of `std::thread`

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?

 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.

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