2017-12-11 41 views
0

クラスメンバ関数をpthread_createに渡して、以下のエラーが発生しています。私はすでにstackoverflow上に非常に多くのクエリがあることを知っているとクラスメンバー関数の周りに静的ヘルパーを作成し、pthread_createの最後の引数としてpthreadと関数のコールバックでその静的関数を渡しているが、私の場合は、また、だから、私の問題は少し違っています。 メンバー関数の引数はどこに渡すべきですか?ご協力いただければ幸いです。引数を持つメンバ関数をC++のpthreadsに渡す

#include <stdio.h> 
#include <pthread.h> 

struct Point 
{ 
    int y; 
    int z; 
}; 

class A 
{ 
    int x; 

    public: 
    int getX(); 
    void setX(int val) {x = val;} 

    void* func(void* args) 
    { 
     Point p = *(Point *)args; 

     int y = p.y; 
     int z = p.z; 

     return (void *)(x + y + z); 
    } 


    void myFunc() 
    { 
     int y = 12; 
     int z = 2; 

     pthread_t tid; 

     Point p; 
     p.y = y; 
     p.z = z; 

     pthread_create(&tid, NULL, func, &p); 
     pthread_join(tid, NULL); 
    } 
}; 

int main(int argc, char *argv[]) 
{ 

    A a; 

    a.myFunc(); 

    return 0; 
} 

エラー:

classThreads.c: In member function ‘void A::myFunc()’: 
classThreads.c:40:42: error: cannot convert ‘A::func’ from type ‘void* (A::)(void*)’ to type ‘void* (*)(void*)’ 
     pthread_create(&tid, NULL, func, &p); 
+0

問題は引数ではなく、メンバ関数のための 'this'ポインタです。 –

+0

私は@JustinFinnertyを知っていますが、解決策も知っていますが、解決策は引数を持たないメンバ関数のためです。引数を持つメンバ関数の解決策が必要です。 –

+2

pthread \ _create関数の '\ * void(MyClass :: \ *)(void \ *)をvoid \ *(\ *)(void \ *)に変換できません]というhttps://stackoverflow.com/question/12006097/can not-convert-voidmyclassvoid-to-voidvoid-in-pthread-create-fu) – VTT

答えて

0

問題は、メソッドを作成するスレッドにthisのポインタを渡していないです。これを引数リストに追加する必要があります。

#include <utility> 
#include <pthread.h> 

struct Point 
{ 
    int y; 
    int z; 
}; 

class A 
{ 
    int x; 

    public: 
    int getX(); 
    void setX(int val) {x = val;} 

    static void* func(void* args) 
    { 
     std::pair< A*, Point > tp = *(std::pair< A*, Point > *)args; 

     int y = tp.second.y; 
     int z = tp.second.z; 

     return (void *)(tp.first->x + y + z); 
    } 


    void myFunc() 
    { 
     int y = 12; 
     int z = 2; 

     pthread_t tid; 

     Point p; 
     p.y = y; 
     p.z = z; 
     std::pair< A*, Point > tp(this, p); 
     pthread_create(&tid, NULL, func, &tp); 
     pthread_join(tid, NULL); 
    } 
}; 

int main(int argc, char *argv[]) 
{ 

    A a; 

    a.myFunc(); 

    return 0; 
} 

あなたはthisポインタと複数の引数を渡すためにstd::tupleクラスを使用することができます。

関連する問題