I'm trying to do a timer class in c++ and I ran into this problem:
I have a start method which creates a thread over a main loop:
static DWORD WINAPI Timer::MainLoop(LPVOID param)
{
Timer* TP = reinterpret_cast<Timer*>(param);
while (true)
{
clock_t now = clock();
unsigned long timeSinceLastExecution = (unsigned long)(now - TP->lastExecution);
if (timeSinceLastExecution >= TP->interval && TP->tick_callback != NULL)
{
TimerMesssage msg;
msg.caller = TP;
msg.timeLastLastCall = timeSinceLastExecution;
TP->tick_callback(1);
TP->lastExecution = clock();
}
}
return 0;
}
void Timer::Start()
{
if (this->mainLoop != NULL)
{
this->Stop();
}
this->currentValue = 0;
this->lastExecution = clock();
mainLoop = CreateThread(NULL, 0, MainLoop, reinterpret_cast<LPVOID>(this), 0, 0);
}
The problem is that
DWORD WINAPI Timer::MainLoop(LPVOID param)
Is not the same as
DWORD WINAPI MainLoop(LPVOID param)
So I can't use the first declaration to crate a thread with that function. I found that I can set it as static as it is in the example above, but then I loss acces to the private members, do you know which is the right way to do this?
Thank you!
Edit: Sorry, typo!
The idea is to use the static method only as a launchpad for the non-static member:
static DWORD WINAPI Timer::MainLoop(LPVOID param)
{
Timer* TP = reinterpret_cast<Timer*>(param);
return TP->MainLoop();
}
// Non-static method
DWORD Timer::MainLoop()
{
while (true)
{
clock_t now = clock();
unsigned long timeSinceLastExecution = (unsigned long)(now - lastExecution);
if (timeSinceLastExecution >= interval && tick_callback != NULL)
{
TimerMesssage msg;
msg.caller = this;
msg.timeLastLastCall = timeSinceLastExecution;
tick_callback(1);
lastExecution = clock();
}
}
return 0;
}
void Timer::Start()
{
if (this->mainLoop != NULL)
{
this->Stop();
}
this->currentValue = 0;
this->lastExecution = clock();
mainLoop = CreateThread(NULL, 0, MainLoop, reinterpret_cast<LPVOID>(this), 0, 0);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.