0

How can I call the thread_ready_function into a thread as commented, using pthread ? I need to call it with the class object (In the real world the function uses attributes previously set).

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;
}
Jean
  • 1,707
  • 3
  • 24
  • 43
  • Can you use c++11 threads? – Brahim Jun 30 '15 at 07:38
  • I will look at c++ 11. But because its support was tricky I think, I want to know if there is a way to achieve this using `pthread` – Jean Jun 30 '15 at 07:48
  • possible duplicate of [pthread Function from a Class](http://stackoverflow.com/questions/1151582/pthread-function-from-a-class) – Ionut Jun 30 '15 at 09:05

1 Answers1

0

if you don't want to use C++11 or stl or boost, you must use the static key word for your member function,so that the pthread can call your member function! example code:

#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; 
}