To be portable the callback function must use the 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;
}
Edit: Based on comment
pthread_join()
This will wait for a particular thread to exit. The thread that called pthread_create() can call pthread_join() to wait for the child to finish. A good place for this would(might) be to put the join in the destructor of the ServerManager.
pthread_cancel()
pthread_cancel() is an asynchronous request for the thread to stop. The call will return immediately (thus does not mean the thread is dead yet). It is unspecified how quickily it will stop executing your code but it should execute some tidy handlers and then exit. It is a good idea to wait for a cancelled thread using 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
};