【发布时间】:2015-08-17 23:24:10
【问题描述】:
我正在尝试用 c++ 做一个计时器类,但遇到了这个问题:
我有一个在主循环上创建线程的 start 方法:
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);
}
问题是
DWORD WINAPI Timer::MainLoop(LPVOID param)
不一样
DWORD WINAPI MainLoop(LPVOID param)
所以我不能使用第一个声明来创建具有该函数的线程。 我发现我可以像上面的例子一样将它设置为静态,但是我失去了对私有成员的访问权限,你知道哪种方法是正确的吗?
谢谢!
编辑:对不起,错字!
【问题讨论】:
-
究竟是什么错误?静态方法可以访问类的私有成员。
-
您是否知道
clock()不测量“挂钟”时间,并且在繁忙的循环中使用线程来检查时间是对 CPU 的严重浪费? -
@tahsmith 编译器说这些成员是不可访问的
-
@Matteo Italia 谢谢!但我会在开始优化之前尝试让它编译
-
下面的答案是正确的,但另一种方法是使用
std::thread,它可以让你使用非静态类成员作为线程进程。
标签: c++ multithreading winapi static-methods