BaseThread.cpp 2.13 KB
#include "BaseThread.h"
#include <stdio.h>
#include <string.h>

CBaseThread::CBaseThread()
{
	m_StopEvent.ResetEvent();
}

CBaseThread::~CBaseThread()
{
}

BOOL CBaseThread::InitInstance()
{
	return TRUE;
}

int CBaseThread::ExitInstance()
{
	return 0;
}

int CBaseThread::Run()
{
	/// @todo implement me
	//inherited class should implement this function to do what the thread will do.
	return 0;
}

void* BaseThreadRun(void* pvParam)
{
	CBaseThread* pBaseThread;
	pBaseThread = (CBaseThread*) pvParam;
	pBaseThread->InitInstance();
	pBaseThread->Run();
	return NULL;
}

BOOL CBaseThread::BeginThread()
{
	/// @todo implement me
	//start the thread.
	int ret;
	ret = pthread_create(&m_thread, NULL, BaseThreadRun, (void*) this);
	if (ret == 0)
		return TRUE;
	else
		return FALSE;
}

void CBaseThread::JoinThread()
{
	/// @todo implement me
	//waiting for the thread to terminate.
	int res;
	void* reStr;

	//if the thread is not created or not available, just return
	if (m_thread == 0)
	{
		CONSOLE_LOG("the thread is null\n");
		return;
	}

	res = pthread_join(m_thread, &reStr);
	CONSOLE_LOG("after thread %lu join, the result = %d\n", m_thread, res);
	if (res != 0)
	{
		CONSOLE_LOG("the join error is %s\n", strerror(res));
		if (res == EDEADLK)
		{
			CONSOLE_LOG("A deadlock was detected\n");
		}
		else if (res == EINVAL)
		{
			CONSOLE_LOG("thread is not a joinable thread\n");
		}
		else if (res == EINVAL)
		{
			CONSOLE_LOG("Another thread is already waiting to join with this thread.\n");
		}
		else if (res == ESRCH)
		{
			CONSOLE_LOG("No thread with the ID thread could be found.\n");
		}
	}

}

void CBaseThread::Shutdown(BOOL bWaitForShutdown)
{
	m_StopEvent.SetEvent();
	if (bWaitForShutdown)
	{
		JoinThread();
	}
	else if (m_thread != 0)
	{
		//不等待子线程结束,让子线程继续运行,将资源回收交给系统
		pthread_detach(m_thread);
	}
}

BOOL CBaseThread::IsStopping(DWORD nTimeOut)
{
	if (m_StopEvent.Wait(nTimeOut) == CON_EVENT_GET_IT)
	{
		m_StopEvent.ResetEvent();
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}