【问题标题】:C++ Thread Inside a Class类中的 C++ 线程
【发布时间】: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


【解决方案1】:

这个想法是只使用静态方法作为非静态成员的启动板:

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

【讨论】:

  • 谢谢!这就是解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多