繁体   English   中英

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

[英]`scoped_thread` pass by value of `std::thread`

我已经从中看到以下实现

运行中的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。

有人可以帮我澄清一下吗?

 scoped_thread t(t1); // pass by value 

那不会编译,因为std::thread是不可复制的(因为它具有move构造函数,但没有copy构造函数)。

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

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

因此,您不必担心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM