类中的c++线程

C++ Thread Inside a Class

本文关键字:线程 c++      更新时间:2023-10-16

我想在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);
}