可能重复:
来自类的pthread函数
我收到一个错误("无法转换....."),我认为pthread_create调用中的第三个参数是错误的.我知道第三个参数的类型应该是(void*)*(void*)但我仍然会收到错误.
void ServerManager::Init(){
pthread_t thread;
pthread_create(&thread, NULL, AcceptLoop, (void *)this);
}
Run Code Online (Sandbox Code Playgroud)
我已经这样声明了,我试着调用下面的函数
void* ServerManager::AcceptLoop(void * delegate){
}
Run Code Online (Sandbox Code Playgroud)
请让我知道如何解决这个问题..
提前致谢.
为了便携,回调函数必须使用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;
}
Run Code Online (Sandbox Code Playgroud)
这将等待特定线程退出.调用pthread_create()的线程可以调用pthread_join()来等待子进程完成.一个好的地方(可能)将连接放在ServerManager的析构函数中.
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
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1217 次 |
最近记录: |