C++ 将方法传递给新线程时出现问题
因此,我在主功能中创建了一个新计时器:C++ 将方法传递给新线程时出现问题,c++,multithreading,C++,Multithreading,因此,我在主功能中创建了一个新计时器: 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 + minu
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;
}
编辑:
它现在可以工作了,但我还是在一开始就崩溃了。所以它崩溃了,但仍然完美地完成了它的工作。我不知道如何修理它
非重要的.h文件
Timer(int seconds = 0, int minutes=0, int hours=0);
新编辑,像这样
class Timer {
private:
std::thread timerThread;
}
销毁线程对象之前,应该先
join()
或detach()
线程对象。否则,将调用std::terminate
在您的情况下,性能良好的解决方案是将std::thread
存储在Timer
对象中,并在析构函数中调用join()
。这是因为您应该将线程视为资源,并使用RAII来管理它们
Timer::~Timer() {
if (timerThread.joinable())
timerThread.join();
}
不能将成员函数直接传递给std::thread。线程需要一个自由函数、一个静态成员函数或一个lambda 使用lambda是最简单的,应该适合您
std::thread newThread([this, totalWaitSeconds]() { startTimer(totalWaitSeconds); });
Timer t1(5)
将使用接受int的单参数构造函数构造一个Timer
对象,您还没有向我们展示。@1201programalm它是同一个构造函数,在.h文件中我有`` Timer(int seconds=0,int minutes=0,int hours=0)```@1201程序这与问题无关,包括所有相关细节(a)。理想情况下,我们可以复制您的代码,在本地编译,并重现错误(仅此而已)。@1201与问题无关的程序。这就是为什么我没有把它包括在我的代码片段中,但是好的。谢谢,我做到了,它成功了,然后我得到了你的答案:D无论如何谢谢你newThread.join();创建线程后,修复了problem@LordNani,我添加了一个关于管理线程的建议。请注意,如果您只是在构造函数中使用join()
,那么构造函数将一直阻塞,直到计时器过期,这可能不一定是您真正想要的,否则您可以从主线程调用std::this_thread::sleep_for
crashes@LordNani,您应该检查joinable()
在调用join()
之前。我不想争论,但它在没有lambdas的情况下可以工作,不知道为什么可能会发生重写。我不能全部记住。正如下面提到的,不要忘记在构造函数之后调用std::thread::join()或更可能的detach()。或者你的应用程序会崩溃。是的,这是问题的一部分,我已经解决了。感谢lambda,我会努力实现它
Timer::~Timer() {
if (timerThread.joinable())
timerThread.join();
}
std::thread newThread([this, totalWaitSeconds]() { startTimer(totalWaitSeconds); });