2016-05-16 84 views
0

我已經在行動看到下面的實現從`scoped_thread`用'的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。

有人可以爲我澄清?

回答

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

這不會編譯,因爲std::thread是不可拷貝(因爲它有一個移動構造函數,而不是拷貝構造函數)。

從現有std::thread構建scoped_thread的唯一方法是通過移動它,這所有權轉移:

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

所以你並不需要擔心。

相關問題