2016-09-19 28 views
7

私のクラス内のスレッドを使用しようとしているときにスレッドがcondition_variableを使用する必要があり、条件変数がブロックされるまで述語はtrueに変更されます。コードは次のようになります。ライン「wait_for」で私のクラスのstd :: thread <未解決のオーバーロードされた関数型>エラー

未解決のオーバーロードされた関数型を:コンパイルに

class myThreadClass{ 
    bool bFlag; 
    thread t ; 
    mutex mtx; 
    condition_variable cv; 

    bool myPredicate(){ 
     return bFlag; 
    } 

    int myThreadFunction(int arg){ 
     while(true){ 
      unique_lock<mutex> lck(mtx); 
      if(cv.wait_for(lck,std::chrono::milliseconds(3000),myPredicate)) //something wrong? 
       cout<<"print something...1"<<endl 
      else 
       cout<<"print something...2"<<endl 
     } 
    } 

    void createThread(){ 
     t = thread(&myThreadClass::myThreadFunction,this,10);//this is ok 
    } 

} ; 

このコードというエラーがスローされます。

その後、私はそれを修正してみてください。

if(cv.wait_for(lck,std::chrono::milliseconds(3000),&myThreadClass::myPredicate)) 

しかし、エラーが依然として存在します。

+2

'(cv.wait_for(lck、std :: chrono :: milliseconds(3000)、[this] {return myPredicate();}))' – ildjarn

+0

述語の使用が間違っています。それが述語が使えない方法です。 –

答えて

4

述語は、コンテキストなしで呼び出し可能である必要があります。非静的なクラスメンバーでこれを呼び出そうとしていますが、これには操作対象のオブジェクトが必要です。

あなたは、オブジェクトのコンテキストをキャプチャし、適切な型に関数呼び出しをラップするためにラムダ関数を使用することができます。

const std::chrono::milliseconds timeout(3000); 
if(cv.wait_for(lck, timeout, [this]{ return myPredicate(); })) 
    // ... 

あなただけのため条件変数のmyPredicateを作成した場合、あなたはそれを離れて行うことができますし、

if(cv.wait_for(lck, timeout, [this]{ return bFlag; })) 
2

はい、実際にこれを行うための最善の方法は..です

auto myPredicate = [this]{ return bFlag; } 
:ちょうどこれを使用します

その後、

if (cv.wait_for(lck, std::chrono::milliseconds(3000), myPredicate)) 

あなたがmyPrediate方法を排除することができるこの方法を使用して。

4

Aオブジェクトにメンバ関数をバインドし、それを作るためにラッパーが必要になりますので、それは、上と呼ばれるようにオブジェクトを必要とするため述語としてメンバ関数(へのポインタ)は、適切ではありません比較する2つの値だけで呼び出し可能です。 C++ 11では

、オブジェクトにメンバ関数をバインドすることができます。

class myThreadClass{ 

bool bFlag; 
thread t ; 
mutex mtx; 
condition_variable cv; 

bool myPredicate(){ 
    return bFlag; 
} 

int myThreadFunction(int arg){ 
    while(true){ 
     unique_lock<mutex> lck(mtx); 
     if(cv.wait_for(lck,std::chrono::milliseconds(3000),std::bind(&myThreadClass::myPredicate,this))) //something wrong? 
      cout<<"print something...1"<<endl; 
     else 
      cout<<"print something...2"<<endl; 
    } 
} 

void createThread(){ 
    t = thread(&myThreadClass::myThreadFunction,this,10);//this is ok 
} 
}; 

あなたは、バインドでプレースホルダを使用することができます。

また、ラムダ関数を使用することもできます。

関連する問題