`scoped_thread`传递`std :: thread`的值

时间:2016-05-16 21:44:35

标签: c++ multithreading

我从

看到了以下实现
  

c ++并发行动

scoped_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;
};

用法示例:

struct func;
void f()
{
    int some_local_state;
    scoped_thread t(std::thread(func(some_local_state)));
    do_something_in_current_thread();
}

如果调用者使用以下代码会发生什么?

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();
}

我担心的是pass by value会导致scoped_thread不拥有线程t1。

有人可以为我澄清吗?

1 个答案:

答案 0 :(得分:4)

scoped_thread t(t1);  // pass by value

那不会编译,因为std::thread不可复制(因为它有一个移动构造函数,但不是复制构造函数)。

从现有scoped_thread构建std::thread的唯一方法是移动它,转移所有权:

scoped_thread t(std::move(t1));

所以你不必担心。