2016-05-16 5 views
0

thread`私は`のstd`の値渡しscoped_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を所有していない原因になりますということです。

誰かが私を明確にすることはできますか? std::threadはコピーできませんので(それは移動コンストラクタではなく、コピーコンストラクタを持っているので)、コンパイルされません

答えて

4
scoped_thread t(t1); // pass by value 

既存std::threadからscoped_threadを構築する唯一の方法は、所有権を転送する、それを移動することである:

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

だから、あなたが心配する必要はありません。

関連する問題