C ++内部类的线程

时间:2015-08-17 23:24:10

标签: c++ multithreading winapi static-methods

我试图用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)

所以我不能使用第一个声明来创建具有该函数的线程。 我发现我可以将它设置为静态,就像上面的例子中一样,但是我失去了对私有成员的访问权限,你知道哪种方法是正确的吗?

谢谢!

编辑:对不起,错字!

1 个答案:

答案 0 :(得分:3)

我们的想法是仅将静态方法用作非静态成员的启动板:

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);
}