我看到了以下的实现
运行中的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。
有人能帮我澄清一下吗?
发布于 2016-05-16 21:46:27
scoped_thread t(t1);//按值传递
这不会编译,因为std::thread是不可复制的(因为它有一个移动构造函数,但没有复制构造函数)。
从现有的scoped_thread构建std::thread的唯一方法是移动它,它转移所有权:
scoped_thread t(std::move(t1));所以你不需要担心。
https://stackoverflow.com/questions/37263758
复制相似问题