#pragma once
#include <pthread.h>
class ThreadWrapper
{
public:
virtual ~ThreadWrapper();
static void EnterFunc(void *p);
int Open();
int Close();
bool TestCancel();
void Wait();
virtual void Svc();
protected:
ThreadWrapper();
private:
bool m_stillOpen;
int m_threadNum;
pthread_t m_handle;
};
*************************************************
#include "ThreadWrapper.h"
ThreadWrapper::ThreadWrapper()
: m_stillOpen(false)
{}
ThreadWrapper::~ThreadWrapper()
{
if(m_stillOpen)
{
Close();
Wait();
}
}
/*
Functional: The enter function of the thread.
*/
void ThreadWrapper::EnterFunc (void *p)
{
ThreadWrapper* bp = static_cast <ThreadWrapper*> (p);
bp->Svc();
}
/*
Functional: Create the thread.
*/
int ThreadWrapper::Open ()
{
m_threadNum = threadNum;
int ret = pthread_create(&m_handle, NULL, EnterFunc, this);
if (ret != 0)
{
return -1;
}
m_stillOpen = true;
return 0;
}
int ThreadWrapper::Close()
{
pthread_cancel(m_handle);
m_stillOpen = false;
return 1;
}
void ThreadWrapper::TestCancel()
{
pthread_testcancel();
}
void ThreadWrapper::Wait()
{
pthread_join(m_handle, NULL);
m_stillOpen = false;
}
void ThreadWrapper::Svc()
{}
此主動對象的用法如下:
1:先定義主動對象類,派生自ThreadWrapper即可,然後實現Svc()虛方法
class Sample : Public ThreadWrapper
{
public:
virtual void Svc()
{
...// add anything you wanna do, and TestCancel() can be positioned somewhere
}
}
2:定義Sample對象,然後open.....
Sample sample;
sample.open(); // 此句執行後線程就開始執行了,即Sample::Svc()開始執行
......
sample.close(); // 主動關閉線程
sample.wait(); // 等待Sample對象的線程執行完畢