// 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;
}