#include <pthread.h>class thread {
public:
thread() {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutex_init(&hRequestEvent, &attr);
pthread_mutexattr_destroy(&attr);
}
virtual ~thread() {
stop();
pthread_mutex_destroy(&hRequestEvent);
}

bool start() {
stop();
pthread_mutex_lock(&hRequestEvent);
pthread_create(&hThread, NULL, &ThreadProc, this); //PTHREAD_CREATE_JOINABLE by default
return true;
}

//stop thread safely, suggest.
bool stop() {
pthread_mutex_unlock(&hRequestEvent);
join();
pthread_detach(hThread); //allow thread to be release once fall into stoped state
return true;
}
bool isStoped() { //added by rene/2012-11-21
return !pthread_mutex_trylock(&hRequestEvent);
}

//terminate thread violently, no suggest.
bool exit() {
pthread_cancel(hThread);
pthread_detach(hThread); //allow thread to be release once fall into stoped state
return true;
}

bool join() {
while(pthread_kill(hThread, 0) == 0) { //the thread is running now
//需要尽快实现分发功能
//这一段是从windows里来的,目的是在等待线程结束时,不断地查找是否有其他消息,如果有的话,则重新分发出去.
//而在mac下不知道怎么实现
//while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { //fixed by rene/2012-04-05
// TranslateMessage(&msg);
// DispatchMessage(&msg);
//}
}
return true;
}
protected:
pthread_mutex_t hRequestEvent;

virtual void OnExecute() = 0;
private:
pthread_t hThread;

static void* ThreadProc(void* lParam) {
thread* th = (thread*)lParam;
if(th)
th->OnExecute();
return 0;
}
};
================
这个类的用法如下:
class CThreadEx: public thread {
void OnExecute() {
for(int i = 0; i < 20; i++) {
if(isStoped()) return; printf("on thread msg---\n");
Sleep(1000);
}
}
};void test() {
thread* th = new CThreadEx();
th->start();
th->join(); //join的功能是等待线程结束之后,再接着做以下的工作.
//问题来了,这时有UI程序会卡在这里,不再响应鼠标键盘等事件了.
//所以想请谁帮我将join里面的代码补充完整.
//... ... delete th;
}