2015-06-30 25 views
0

如何使用pthread将thread_ready_function调用为注释的线程?我需要用类对象调用它(在现实世界中,函数使用之前设置的属性)。使用pthread调用对象的成员函数

MWE

#include <iostream> 
#include <pthread.h> 


class ClassA 
{ 
public: 

    void * thread_ready_function(void *arg) 
    { 
     std::cout<<"From the thread"<<std::endl; 

     pthread_exit((void*)NULL); 
    } 
}; 

class ClassB 
{ 
    ClassA *my_A_object; 
public: 
    void test(){ 
     my_A_object = new ClassA(); 

     my_A_object->thread_ready_function(NULL); 

     // my_A_object->thread_ready_function(NULL); 
     //^
     // I want to make that call into a thread. 

     /* Thread */ 
/* 
     pthread_t th; 
     void * th_rtn_val; 

     pthread_create(&th, NULL, my_A_object.thread_ready_function, NULL); 
     pthread_join(th, &th_rtn_val); 
*/ 
    } 
}; 

int main() 
{ 
    ClassB *my_B_object = new ClassB(); 
    my_B_object->test(); 

    return 0; 
} 
+0

你可以使用C++ 11线程吗? – Brahim

+0

我会看看C++ 11.但是因为它的支持很棘手,我想,我想知道是否有一种方法可以使用'pthread'来实现这一点[ – JeanRene

+0

] [pthread Function from a class](http:// stackoverflow .COM /问题/ 1151582 /并行线程功能,从-A级) – Ionut

回答

0

,如果你不希望使用C++ 11或STL或升压,你必须使用静态关键字为您的成员函数,使并行线程可以致电您的会员功能! 示例代码:

#include <iostream> 
#include <pthread.h> 

using namespace std; 

class A{ 
    public: 
    static void* thread(void* args); 
    int parella_thread(int thread_num); 
}; 

void* A::thread(void* args) 
{ 
    cout<<"hello world"<<endl; 
} 

int A::parella_thread(int thread_num) 
{ 
    pthread_t* thread_ids = new pthread_t[thread_num]; 
    for(int i=0;i<thread_num;i++) 
    { 
    pthread_create(&thread_ids[i],NULL,thread,(void*)NULL); 
    } 
    delete[] thread_ids; 
} 

int main(int argc,char*argv[]) 
{ 
    A test; 
    test.parella_thread(4); 
    return 0; 
} 
相关问题