LoginSignup
22
23

More than 5 years have passed since last update.

【C++11】threadでメンバ関数を指定するには?

Posted at

C++11でthreadやmutexなどがサポートされたと知ったので
(調べるのもめんどくさいし)システム依存のAPIを使いたくないマン
としてはひとまず使ってみたものの、ちゃんと理解してなかったためとあるコンパイルエラーにひっかかった話。

以下、とりあえずstd::threadを使って組んでみたプログラム

sample
#include <thread>
using namespace std;

class ThreadClass
{
public:
    ThreadClass();
    ~ThreadClass();

    void ThreadStart();
    void MainThread( int param );
};

ThreadClass::ThreadClass()
{
    //constractor
}

ThreadClass::~ThreadClass()
{
    //destractor
}

void ThreadClass::ThreadClass()
{
    // thread create
    std::thread th( &ThreadClass::MainThread, 5 ); // パラメータは適当

    // thread start
    th.detach();
}

void ThreadClass::MainThread( int param )
{
    bool bLoop = true; // thread control flag
    while( bLoop )
    {
       param--;
       if( param == 0 )
       {
          bLoop = false;
       }
    }
}

int main()
{
    ThreadClass* pcThread = new ThreadClass();
    pcThread->ThreadStart();

    return 0;
}

これでコンパイルを実行すると

error C2064: 1 引数を取り込む関数には評価されません。
というエラーが・・・

何がおかしいのか途方にくれながら色々ググってると
どうやらスレッドにメンバ関数を指定する場合は第2引数にthisを渡す
ことが必要らしい。

なので以下のように修正してみる。

std::thread th( &ThreadClass::MainThread, 5 );
これを
std::thread th( &ThreadClass::MainThread, this, 5 );
こうすることで、コンパイルも通りちゃんと動作してくれるようになった。

ちゃんと理解しないまま適当にやるからこうなるいい教訓

22
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
23