您的位置:首页 > 其它

pthread_create in class method

2013-10-08 10:44 204 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐