类中的c++线程
C++ Thread Inside a Class
我想在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)
所以我不能使用第一个声明来创建一个带有该函数的线程。我发现我可以将它设置为静态,就像上面的例子一样,但这样我就失去了对私有成员的访问权限,你知道哪一种方法是正确的吗?
谢谢!
编辑:对不起,打错了!我们的想法是将静态方法仅用作非静态成员的启动平台:
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);
}
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- 为什么我不能在 while 循环中创建线程?