#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对象的线程执行完毕