p ++中的pthread_create错误

时间:2011-06-15 02:15:01

标签: c++ pthreads

  

可能重复:
  pthread Function from a Class

我收到错误(“无法转换.....”),我认为pthread_create调用中的第三个参数是错误的。我知道第三个参数的类型应该是(void *)*(void *)但我仍然会收到错误。

void ServerManager::Init(){  
     pthread_t thread;
     pthread_create(&thread, NULL, AcceptLoop, (void *)this);
}

我已经这样声明了,我正在尝试调用下面的函数

void* ServerManager::AcceptLoop(void * delegate){

}

请让我知道如何解决这个问题..

提前致谢。

2 个答案:

答案 0 :(得分:5)

要便携,回调函数必须使用C ABI;

extern "C" void* AcceptLoop(void*);

class ServerManager 
{
    public:
       void  Init();

    private:
       friend void* AcceptLoop(void*);

       void* AcceptLoop();   // Implement this yourself
       pthread_t thread;
};

void ServerManager::Init()
{  
     pthread_create(&thread, NULL, &AcceptLoop, reinterpret_cast<void*>(this));
}

void* AcceptLoop(void* delegate)
{
    return reinterpret_cast<ServerManager*>(delegate)->AcceptLoop();
}

void* ServerManager::AcceptLoop()
{
    // Do stuff
    // Be carefull this may (or may not) start before ServerManager::Init() returns.
    return NULL;
}

编辑:基于评论

在pthread_join()

这将等待特定线程退出。调用pthread_create()的线程可以调用pthread_join()来等待子进程完成。一个好的地方(可能)将连接放在ServerManager的析构函数中。

pthread_cancel可以()

pthread_cancel()是要停止的线程的异步请求。调用将立即返回(因此并不意味着线程已经死亡)。未指定它将如何快速地停止执行代码,但它应该执行一些整洁的处理程序然后退出。使用pthread_jon()等待取消的线程是个好主意。

class ServerManager 
{
    public:
       void  ~ServerManager()
       {
           join();
       }
       void* join()
       {
           void*   result;
           pthread_join(thread, &result);
           return result;
       }
       void cancel()
       {
           pthread_cancel(thread);
           join();
       }
       ... like before
};

答案 1 :(得分:2)

您需要使AcceptLoop(void*)成为静态函数。

示例:

class ServerManager {
    // ...
    static void* AcceptLoop(void*);
    void* AcceptLoop();   // Implement this yourself
};

void* ServerManager::AcceptLoop(void* delegate)
{
    return static_cast<ServerManager*>(delegate)->AcceptLoop();
}