注意C++类中的static函数,具体原因请参考《win32多线程程序设计》中相关章节。
#include <windows.h> #include <process.h> #include <stdlib.h> #include <stdio.h> #include <TCHAR.h> #include <iostream> using namespace std;
typedef unsigned (WINAPI *PBEGINTHREADEX_THREADFUNC)(LPVOID lpThreadParameter);
class ThreadObject { public: ThreadObject(); void StartThread(); void WaitForExit();
static DWORD WINAPI ThreadFunc(LPVOID param); protected: virtual DWORD ThreadMemberFunc(); HANDLE m_hThread; DWORD m_ThreadId; };
ThreadObject::ThreadObject() { m_hThread = NULL; m_ThreadId = 0; }
void ThreadObject::StartThread() { m_hThread = (HANDLE)_beginthreadex(NULL,0, (PBEGINTHREADEX_THREADFUNC)ThreadObject::ThreadFunc, (LPVOID)this, 0, (unsigned *)&m_ThreadId); if(m_hThread){ cout<<"Thread lanched\n"; } }
void ThreadObject::WaitForExit() { WaitForSingleObject(m_hThread, INFINITE); cout<<"The Main Thread exit\n"; CloseHandle(m_hThread); }
DWORD WINAPI ThreadObject::ThreadFunc(LPVOID param) { ThreadObject *pto = (ThreadObject*)param; return pto->ThreadMemberFunc(); }
DWORD ThreadObject::ThreadMemberFunc() { int i; for(i=0;i<5;i++){ cout<< " thread do "<<i<<endl; Sleep(1000); } return 0; }
int main(int argc,char **argv[]) { ThreadObject obj; obj.StartThread(); obj.WaitForExit(); }
|
阅读(1047) | 评论(0) | 转发(0) |