thread.cpp
#include "thread.hpp"
Thread::Thread()
:m_stopFlag(false)
,m_hThread(INVALID_HANDLE_VALUE)
{
}
Thread::~Thread()
{
Stop();
}
void Thread::Start()
{
unsigned long *p =NULL;
m_hThread = ::CreateThread(NULL, 0, ThreadProc, this, 0, p);
}
DWORD WINAPI Thread::ThreadProc(LPVOID p)
{
Thread* thread = (Thread*)p;
thread->Run();
CloseHandle( thread->m_hThread );
thread->m_hThread= INVALID_HANDLE_VALUE;
return 0;
}
void Thread::Stop()
{
m_stopFlag = true;
if(m_hThread != INVALID_HANDLE_VALUE)
{
if(WaitForSingleObject(m_hThread,INFINITE) != WAIT_ABANDONED)
{
CloseHandle(m_hThread);
}
m_hThread = INVALID_HANDLE_VALUE;
}
}
bool Thread::IsStop()
{
return m_stopFlag;
}
thread.hpp
#ifndef _THREAD_H_
#define _THREAD_H_
#include <Windows.h>
class Thread
{
public:
Thread();
virtual ~Thread();
virtual void Run() = 0;
void Start();
void Stop();
bool IsStop();
protected:
static DWORD WINAPI ThreadProc(LPVOID p);
private:
bool m_stopFlag;
HANDLE m_hThread;
};
#endif
time.hpp
#ifndef _TIMER_H_
#define _TIMER_H_
#include <Windows.h>
#include "thread.hpp"
class Timer : public Thread
{
typedef void(CALLBACK *Timerfunc)(void* p);
typedef Timerfunc TimerHandler;
public:
Timer()
:m_handler(0)
,m_interval(-1)
{
}
void registerHandler(TimerHandler handler, void* p)
{
m_handler = handler;
m_parameter = p;
}
void setInterval(int millisecond)
{
m_interval = millisecond;
}
void Run()
{
unsigned long tickNow = ::GetTickCount();
unsigned long tickLastTime = tickNow;
while(!IsStop())
{
tickNow = ::GetTickCount();//timer to run thread!
if(tickNow - tickLastTime > m_interval)
{
if(m_handler)
{
(*m_handler)(m_parameter);
}
tickLastTime = ::GetTickCount();
}
::Sleep(1);
}
}
void Cancel()
{
Stop();
}
private:
TimerHandler m_handler;
int m_interval;
void* m_parameter;
};
#endif
main.cpp
#include "time.hpp"
#include "thread.hpp"
#include <iostream>
struct my_struct
{
bool a;
int b;
};
void CALLBACK TimerProc(void* p)
{
std::cout << "time is up"<< std::endl;
std::cout << ((*(my_struct*)p).a) << std::endl;
std::cout << ((*(my_struct*)p).b) << std::endl;
}
int main(int argc, char **argv) {
my_struct c;
c.a = false;
c.b = 0;
Timer timer;
timer.registerHandler(TimerProc, &c);
timer.setInterval(1000);//定时1000ms
timer.Start();
//while (true)
{
for (; c.b < 10; c.b++)
{
Sleep(1000);
}
}
return 0;
}