代碼如下:
// Thread.cpp :win32線程庫,目前只能是示範的強度
// 作者 :galphy 2005-6-20
//////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <stdio.h>
typedef unsigned long (__stdcall * THREADFUNC)(void *);
class Runnable {
public:
/**
* Runnables should never throw in their destructors
*/
virtual ~Runnable() {}
/**
* Task to be performed in another thread of execution
*/
virtual void run() = 0;
friend THREADFUNC do_work(Runnable *run);
};
/**
* 線程的回呼函數
*/
namespace THREADWORK{
THREADFUNC do_work(Runnable *runnable)
{
if(runnable)
runnable->run();
return 0;
}
}
class Thread
{
public:
/**
*
*/
//void Exit()
//{
// if(true)
// {
// ExitThread(exitCode);
// }
//}
/**
*
*/
//void Stop()
//{
// DWORD status;
// int i;
// for(i=0; i<200; i++)
// {
// if( ::GetExitCodeThread(m_Handle, &status) && status==STILL_ACTIVE ) Sleep(10);
// else break;
// }
// if(i >= 200) Kill(); //2秒還不停下來就把它KILL掉
//}
/**
* 殺死線程
*/
BOOL Kill()
{
if(m_Handle)
{
return TerminateThread(m_Handle,exitCode);
}
}
/**
* 建立線程
*/
Thread(Runnable *runnable)
{
m_ThreadId = 0;
m_Handle = NULL;
exitCode = 0;
m_Handle = CreateThread(0 , 0 , (THREADFUNC) THREADWORK::do_work , (void *)runnable , CREATE_SUSPENDED , &m_ThreadId);
}
/**
* 啟動線程
*/
DWORD Resume()
{
if(m_Handle)
{
return ResumeThread(m_Handle);
}
else
{
return 0;
}
}
/**
* 掛起線程
*/
DWORD Suspend()
{
if(m_Handle)
{
return SuspendThread(m_Handle);
}
else
{
return 0;
}
}
/**
* 清除線程
*/
~Thread()
{
if(m_Handle)
{
CloseHandle(m_Handle);
}
m_ThreadId = 0;
m_Handle = NULL;
exitCode = 0;
}
private:
DWORD m_ThreadId;
HANDLE m_Handle;
DWORD exitCode;
};
class Test : public Runnable
{
public:
Test(){};
~Test(){};
void run()
{
for(int i = 0 ; i < 10000000 ; i++)
{
printf("%d-------------/n", i);
}
}
private:
int a;
};
//測試主程式
int main(int argc, char* argv[])
{
Thread mythread(new Test());
mythread.Resume();
Sleep(1000);
mythread.Suspend();
Sleep(1000);
return 0;
}