条件编译 实现 android和windows上线程创建

来源:互联网 发布:mac 屏幕睡眠时间 编辑:程序博客网 时间:2024/06/05 03:19
// Thread.cpp: 


#include "CThread.h"


CThread::CThread()
{
#ifdef OS_WINDOWS
    m_hThread = NULL;
#endif
}


CThread::~CThread()

#ifdef OS_WINDOWS
    if (NULL != m_hThread)
    {
        CloseHandle(m_hThread);
    } 
#endif
}


#ifdef OS_WINDOWS
THREAD_HANDLE CThread::create(void(*pThreadFun)(void*), void* arg)
{
    UINT uiThreadID;
    m_hThread = (HANDLE)(::_beginthreadex(NULL, NULL, (WIN32threadFun)pThreadFun, arg, NULL, &uiThreadID));


return m_hThread;
}
#endif


#ifdef ANDROID
THREAD_HANDLE CThread::create(void*(*pThreadFun)(void*), void* arg)
{
int result = pthread_create(&m_hThread,NULL,(LINUXthreadFun)pThreadFun,arg);
if (result)
{
return 0;
}


return m_hThread;
}
#endif




void CThread::sleep(int ms)
{
#ifdef ANDROID
pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER;
struct timespec timeToWait;
struct timeval now;
int rt;


gettimeofday(&now,NULL);


long seconds = ms/1000;
long nanoseconds = (ms - seconds * 1000) * 1000000;
timeToWait.tv_sec = now.tv_sec + seconds;
timeToWait.tv_nsec = now.tv_usec*1000 + nanoseconds;


if (timeToWait.tv_nsec >= 1000000000)
{
timeToWait.tv_nsec -= 1000000000;
timeToWait.tv_sec++;
}


pthread_mutex_lock(&fakeMutex);
rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
pthread_mutex_unlock(&fakeMutex);
#endif


#ifdef OS_WINDOWS
Sleep(ms);
#endif
}


void CThread::exit(int code)
{
#ifdef ANDROID
pthread_exit((void*)code);
#endif


#ifdef OS_WINDOWS
_endthreadex(code);
#endif
}
0 0
原创粉丝点击