在cocoa下不知道怎么实现等待一个线程结束.
超级怀念windows的WaitForSingle函数.
下面window下一个包装,有谁可以翻译成mac的功能?
#pragma once
#include <windows.h>
#define INVALID_PRIORITY -88888888
class thread {
public:
thread(): hThread(0) {
hRequestEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
}
virtual ~thread() {
stop();
CloseHandle(hRequestEvent);
}
//set thread name, that's usually invoked in the OnExecute of subclass
void named(const char* name) { //fixed by rene/2012-05-21
typedef struct tagTHREADNAME_INFO {
DWORD dwType; //must be 0x1000
LPCSTR szName; //pointer to name (in user addr space)
DWORD dwThreadID; //thread ID (-1=caller thread)
DWORD dwFlags; //reserved for future use, must be zero
} THREADNAME_INFO;
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = -1;
info.dwFlags = 0;
__try {
RaiseException(0x406D1388, 0, sizeof(info) / sizeof(DWORD), (const DWORD*)&info);
}
__except(EXCEPTION_CONTINUE_EXECUTION) {}
}
bool start() {
stop();
ResetEvent(hRequestEvent);
DWORD dwThreadId;
hThread = CreateThread(NULL, 0, ThreadProc, this, 0, &dwThreadId);
return true;
}
//stop thread safely, suggest.
bool stop() { //fixed by rene/2012-04-24
SetEvent(hRequestEvent);
join();
if(hThread)
CloseHandle(hThread);
hThread = NULL;
return true;
}
//terminate thread violently, no suggest.
bool exit() { //fixed by rene/2012-05-22
TerminateThread(hThread, 0); //ExitThread(0);
if(hThread)
CloseHandle(hThread);
hThread = NULL;
return true;
}
bool join() {
DWORD exitCode;
if(GetExitCodeThread(hThread, &exitCode) && exitCode == STILL_ACTIVE) {
DWORD dwRet = 0;
MSG msg;
while(TRUE) {
//using MsgWaitForMultipleObjects instead of WaitForSingleObject.
//because of invoking SendMessage in thread.
//otherwise, it will block the thread.
dwRet = MsgWaitForMultipleObjects(1, &hThread, FALSE, INFINITE, QS_ALLINPUT); //fixed by rene/2012-04-05
if(dwRet == WAIT_OBJECT_0 + 1) {
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { //fixed by rene/2012-04-05
TranslateMessage(&msg);
DispatchMessage(&msg);
}
continue;
}
break;
}
}
return true;
}
bool pause() {
//if(hThread)
SuspendThread(hThread);
return true;
}
bool resume() {
//if(hThread)
ResumeThread(hThread);
return true;
}
/******************************************************