将方法传递给新线程时出现问题



所以我在主函数中创建了一个新的计时器:

int main(){
Timer t1(5);
return 0;
}

这是我的建设者

Timer::Timer(int seconds, int minutes, int hours) : myID(freeID++) {
_currentTime = Time::getDefault();
_currentDate = Date::getDefault();
int totalWaitSeconds = seconds + minutes * 60 + hours * 60 * 60;
std::thread newThread(&Timer::startTimer,this, totalWaitSeconds);
}
void Timer::startTimer(int start) {
while (start > 0) {
this_thread::sleep_for(1s);
--start;
}
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
<< "            !!!DING DING DING!!!"
<< "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" 
<< "Timer with ID[" << this->myID << "], went off"
<< endl;
}

我不知道如何将方法传递给具有所需值的线程。当我尝试这样做时,要么我得到运行时错误(中止(,要么它说没有匹配重载std::invoke:

std::thread newThread(&Timer::startTimer, totalWaitSeconds);

编辑:它现在起作用了,但一开始我还是崩溃了。所以它崩溃了,但仍然完美地完成了它的工作。我不知道如何修复

非重要.h文件

Timer(int seconds = 0, int minutes=0, int hours=0); 

新编辑,像这样?:

class Timer {
private:
std::thread timerThread;
}
Timer::Timer(int seconds, int minutes, int hours) : myID(freeID++) {
_currentTime = Time::getDefault();
_currentDate = Date::getDefault();
int totalWaitSeconds = seconds + minutes * 60 + hours * 60 * 60;
timerThread = thread(&Timer::startTimer,this, totalWaitSeconds);
}
Timer::~Timer() {
timerThread.join();
}

在销毁join()detach()线程对象之前,应该先使用它。否则,thread析构函数将调用std::terminate

在您的情况下,行为良好的解决方案是将std::thread存储在Timer对象中,并在析构函数中调用join()。这是因为您应该将线程视为资源,并使用RAII来管理它们。

Timer::~Timer() {
if (timerThread.joinable())
timerThread.join();
}

不能将成员函数直接传递给std::thread。std::thread需要一个自由函数、一个静态成员函数或一个lambda。

使用lambda是最简单的,应该对您有效。

std::thread newThread([this, totalWaitSeconds]() { startTimer(totalWaitSeconds); });

最新更新