#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<pthread.h>
#include<queue>
#include<string>
#include<string.h>
using namespace std;
/*************************************
*author:郑金玮
*time:2014/07/16
*desc:implement thread package in cpp class at linux
********************************** */
typedef unsigned int uint32;
typedef int int32;
typedef int64_t uint64;
typedef short int16;
typedef unsigned short uint16;
typedef unsigned long bc_dword;
typedef unsigned short bc_word;
typedef unsigned char bc_byte;
typedef size_t bc_size;
typedef void* bc_HANDLE;
#define DISALLOW_CPY_ASSIGN(type) private: \
type(const type&); \
type& operator = (const type&);
class CThreadLinux
{
public:
CThreadLinux();
virtual ~CThreadLinux();
int GetHandle() const;
void Start();
bc_dword Terminate(bc_dword exitCode = 0);
public:
virtual int Run() =0;
static void* ThreadFunction(void *PV);
void ResetHandle();
DISALLOW_CPY_ASSIGN(CThreadLinux);
private:
int32 m_hThread;
};
CThreadLinux::CThreadLinux()
{
m_hThread = 0;
}
CThreadLinux::~CThreadLinux()
{
ResetHandle();
}
int CThreadLinux::GetHandle() const
{
return m_hThread;
}
void CThreadLinux::Start()
{
if(m_hThread == 0)
{
pthread_t __ntid;
m_hThread = pthread_create(&__ntid,0,ThreadFunction,(void*)this);
}
}
bc_dword CThreadLinux::Terminate(bc_dword exitCode)
{
if(m_hThread != 0)
{
pthread_exit(NULL);
return 0;
}
return 0;
}
void* CThreadLinux::ThreadFunction(void *PV)
{
CThreadLinux *pThis = (CThreadLinux*)PV;
int32 __ret = pThis->Run();
pthread_detach(pthread_self());// set thread mode to nonblock mode and return now
pThis->ResetHandle();
return NULL;
}
void CThreadLinux::ResetHandle()
{
if(m_hThread != NULL)
{
m_hThread = 0;
}
}
/this is a demo for test thread function//
class CLog : public CThreadLinux
{
private:
CLog(){}
~CLog(){}
public:
static CLog* instance();
void log(string strlog)
{
m_msgQueue.push(strlog);
}
int Run()
{
while(true)
{
if(!m_msgQueue.empty())
{
cout<<m_msgQueue.front()<<"\n"<<endl;
fflush(stdout);
m_msgQueue.pop();
}
}
return 0;
}
private:
queue<string> m_msgQueue;
};
CLog* CLog::instance()
{
static CLog __instance;
return &__instance;
}
#define LOG() CLog::instance()
int main()
{
int32 num = 1000;
int32 i=1;
char szLogs[256];
LOG()->Start();
while( i <= num )
{
memset(szLogs,0,256);
sprintf(szLogs,"log index %d",i);
LOG()->log(szLogs);
i++;
}
for(;;);
return 0;
}