创建一个线程并调用一个类的函数

时间:2016-06-07 04:56:40

标签: c++ multithreading struct pthreads

如何在创建线程时访问类的功能?

当我删除它时,它运行良好,只要我不必使用对象来访问该函数。

另外,我收到此错误:error: argument of type ‘void* (MyClass::)(void*)’ does not match ‘void* (*)(void*)’

#include <iostream>
#include <pthread.h>
using namespace std;

struct thread_data
{
    int tid;
    char *msg;
};

class MyClass
{
public:
    void *MyFunction(void *myarg)
    {

        struct thread_data *td = (struct thread_data *)myarg;
        cout << "Inside MyFunction With Thread Id : " << td->tid << endl;
        cout << "Message Of Thread Id " << td->tid << " is : "<< td->msg << endl;
        //sleep(1);
        pthread_exit(NULL);
    }
};

int main()
{
    MyClass o1,o2,o3;
    pthread_t obj1,obj2,obj3;
    struct thread_data td1,td2,td3;

    td1.tid=1;
    td1.msg="First Thread";

    pthread_create(&obj1,NULL,o1.MyFunction,(void *)&td1);

    td2.tid=2;
    td2.msg="Second Thread";

    pthread_create(&obj2,NULL,o2.MyFunction,(void *)&td2);

    td3.tid=3;
    td3.msg="Third Thread";

    pthread_create(&obj3,NULL,o3.MyFunction,(void *)&td3);

    pthread_exit(NULL);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

你可以使用boost来做到这一点:

class MyClass
{
    void myFunction(void* arg) {};
};

boost::function<void(void)> f = boost::bind(&MyClass::myFunction,&MyClassInstance,&MyStructInstance); 
boost::function<void(void)>* fCopy = new boost::function<void(void)> (function); //create a copy on the heap

void wrappedFunction(void* arg)
{

   boost::function<void(void)> *func = (boost::f<void(void)>* ) (arg);
   (*func)();
   delete(func);
}

pthread_t id;
pthread_create(&id,NULL,&wrappedFunction,functionCopy);