當我想要使用類來封裝server的時候,遇到之前的pthread_create() 接口不能直接使用的情況,這樣必須要把相關的綫程函數設置成static的模式,
class C
{
public:
void *hello(void)
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
而問題又來了,static函數只能調用static變量,這樣就變成了函數無法使用非static成員變量了。
而又找到了以下非常騷代碼
typedef void * (*THREADFUNCPTR)(void *);
// Pointer to object of class Task
Task * taskPtr = new Task();
//Thread ID
pthread_t threadId;
// Create thread using memeber function as startup routine
pthread_create(&threadId, NULL, (THREADFUNCPTR) &Task::execute,taskPtr);