2015-06-30 28 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; 
} 
相關問題