pthread_create can not use class normal methods directly, but can use static methods. Here is a example:
//g++ -o test test.c -lpthread
#include <iostream>
#include <pthread.h>
using namespace std;
class Testing
{
private:
//cLog* m_Log;
pthread_t tid; // would one suffice? // std::vector<pthread_t> tids ; ?
public:
Testing( );
~Testing( );
void floodLog( int nThreads );
private:
void* writeToLog( void* );
static void* thread_fun( void* args ) ;
struct thread_fun_args
{
Testing* This ; // other args as required; in this case
void* actual_arg ;
thread_fun_args( Testing* t, void* p ): This(t), actual_arg(p) {}
};
};
Testing::Testing( )
{
cout << "Called constructor of Testing...\n";
}
Testing::~Testing( )
{
cout << "Called Desconstructor of Testing...\n";
}
void* Testing::writeToLog( void* )
{
return NULL;
}
void Testing::floodLog( int nThreads )
{
cout << "Flooding cLog class with " << nThreads << " threads.\n";
for( int i = 0; i < nThreads; i++ )
{
cout << "Created Thread: " << ( i + 1 ) << endl;
pthread_create( &tid, NULL, &Testing::thread_fun,
new thread_fun_args(this,0) );
}
cout << "Finished flooding.\n";
}
void* Testing::thread_fun( void* pv )
{
thread_fun_args* tf_args = static_cast<thread_fun_args*>(pv) ;
Testing* This = tf_args->This ;
void* args = tf_args->actual_arg ;
void* result = This->writeToLog( args ) ;
delete tf_args ;
return result ;
}
int main()
{
Testing t;
t.floodLog(2);
return 0;
}
Cited from http://www.daniweb.com/forums/thread115838.html