2017-06-11 6 views
3

ActionのC++並行処理でサンプルをテストするときに問題が発生します。C++でのスレッドの移動11

/*** 
Scoped_thread 
Help explain the move semantics of Scoped_guard 
@c++ Concurrency in Action 
***/ 
#include <thread> 
#include <iostream> 
using namespace std; 
class Scoped_thread 
{ 
    std::thread t; 
public: 
    Scoped_thread(std::thread _t): 
    t(std::move(_t)) 
    { 
     cout << "Success?" << endl; 
     if (!t.joinable()) 
     throw std::logic_error("No thread"); 
    } 
    ~Scoped_thread() 
    { 
    t.join(); 
    } 
    Scoped_thread(Scoped_thread const&) = delete; 
    Scoped_thread& operator=(Scoped_thread const&) = delete; 
}; 

struct func 
{ 
    int& i; 
    func(int& i):i(i) {} 
    void operator()() 
    { 
    for (unsigned j = 0; j < 1000000; j++) 
    { 
     cout << j << endl; 
    } 
    } 
}; 

int main() 
{ 
    int some_local_state = 1; 
    func myfunc(some_local_state); 
    Scoped_thread t2(std::thread(myfunc)); 
    for (unsigned j = 0; j < 1000; j++) 
    { 
    cout << "Main thread " << j << endl; 
    } 
} 

「メインスレッド」のみが表示されます。コンストラクタが起動していないことがわかりました。これは、スレッド移動セマンティクスを使用していくつかの問題を示していますか? 私の作業環境は、Ubuntuの16.04で、コンパイルコマンドは、 'G ++ -std = C++ 11 -Wall -pthread file.cpp' です

答えて

1
Scoped_thread t2(std::thread(myfunc)); 

ここでは、most vexing parseのやや非従来のケースを持っています。事がある:次の関数フォワード宣言は等価である:

void f(int arg); 
void f(int (arg)); 

したがって、Scoped_thread t2(std::thread(myfunc));Scoped_threadを返し、引数としてstd::thread myfuncを取る関数t2の前方宣言として解析されます。

二つの解決策は以下のとおりです。

Scoped_thread t2{std::thread(myfunc)}; 
関連する問題