103 lines
1.8 KiB
C++
103 lines
1.8 KiB
C++
#include "HGThread.h"
|
|
#include "HGInc.h"
|
|
|
|
struct HGThreadImpl
|
|
{
|
|
HGThreadImpl()
|
|
{
|
|
#if !defined(HG_CMP_MSC)
|
|
m_ntid = 0;
|
|
#else
|
|
m_thread = NULL;
|
|
#endif
|
|
m_func = NULL;
|
|
m_param = 0;
|
|
}
|
|
|
|
~HGThreadImpl()
|
|
{
|
|
#if !defined(HG_CMP_MSC)
|
|
if (0 != m_ntid)
|
|
{
|
|
pthread_join(m_ntid, NULL);
|
|
m_ntid = 0;
|
|
}
|
|
#else
|
|
if (NULL != m_thread)
|
|
{
|
|
WaitForSingleObject(m_thread, INFINITE);
|
|
CloseHandle(m_thread);
|
|
m_thread = NULL;
|
|
}
|
|
#endif
|
|
m_param = 0;
|
|
m_func = NULL;
|
|
}
|
|
|
|
#if !defined(HG_CMP_MSC)
|
|
static void* thread_fun(void* arg)
|
|
{
|
|
HGThreadImpl* p = (HGThreadImpl*)arg;
|
|
p->m_func((HGThread)p, p->m_param);
|
|
return NULL;
|
|
}
|
|
#else
|
|
static DWORD WINAPI ThreadCallback(LPVOID param)
|
|
{
|
|
HGThreadImpl* p = (HGThreadImpl*)param;
|
|
p->m_func((HGThread)p, p->m_param);
|
|
return 0;
|
|
}
|
|
#endif
|
|
|
|
#if !defined(HG_CMP_MSC)
|
|
pthread_t m_ntid;
|
|
#else
|
|
HANDLE m_thread;
|
|
#endif
|
|
HGThreadFunc m_func;
|
|
HGPointer m_param;
|
|
};
|
|
|
|
HGResult HGAPI HGBase_OpenThread(HGThreadFunc func, HGPointer param, HGThread* thread)
|
|
{
|
|
if (NULL == func || NULL == thread)
|
|
{
|
|
return HGBASE_ERR_INVALIDARG;
|
|
}
|
|
|
|
HGThreadImpl* threadImpl = new HGThreadImpl;
|
|
threadImpl->m_func = func;
|
|
threadImpl->m_param = param;
|
|
|
|
#if !defined(HG_CMP_MSC)
|
|
if (0 != pthread_create(&threadImpl->m_ntid, NULL, HGThreadImpl::thread_fun, threadImpl))
|
|
{
|
|
delete threadImpl;
|
|
return HGBASE_ERR_FAIL;
|
|
}
|
|
#else
|
|
threadImpl->m_thread = CreateThread(NULL, 0, HGThreadImpl::ThreadCallback, threadImpl, 0, NULL);
|
|
if (NULL == threadImpl->m_thread)
|
|
{
|
|
delete threadImpl;
|
|
return HGBASE_ERR_FAIL;
|
|
}
|
|
#endif
|
|
|
|
* thread = (HGThread)threadImpl;
|
|
return HGBASE_ERR_OK;
|
|
}
|
|
|
|
HGResult HGAPI HGBase_CloseThread(HGThread thread)
|
|
{
|
|
if (NULL == thread)
|
|
{
|
|
return HGBASE_ERR_INVALIDARG;
|
|
}
|
|
|
|
HGThreadImpl* threadImpl = (HGThreadImpl*)thread;
|
|
delete threadImpl;
|
|
return HGBASE_ERR_OK;
|
|
}
|