我实现了一个周期性运行提供的函数的类。
//Timer.h
#include <chrono>
#include <mutex>
#include <thread>
class Timer {
public:
Timer(const std::chrono::milliseconds period, const std::function<void()>& handler);
~Timer();
void Start();
void Stop();
bool IsRunning() const;
private:
const std::function<void()>& handler;
const std::chrono::milliseconds period;
bool isRunning = false;
mutable std::recursive_mutex lock;
int counter = 0;
void DoLoop(int id);
};
//Timer.cpp
#include "Timer.h"
Timer::Timer(const std::chrono::milliseconds period, const std::function<void()>& handler) :handler(handler), period(period), lock(){}
Timer::~Timer() {
Stop();
}
void Timer::Stop() {
lock.lock();
isRunning = false;
lock.unlock();
}
void Timer::Start() {
lock.lock();
if (!isRunning) {
isRunning = true;
counter++;
std::thread(&Timer::DoLoop, this, counter).detach();
}
lock.unlock();
}
void Timer::DoLoop(int id) {
while (true){
std::this_thread::sleep_for(period);
lock.lock();
bool goOn = isRunning && counter==id;
if (goOn) std::thread(handler).detach();
lock.unlock();
if (!goOn)
break;
}
}
bool Timer::IsRunning() const {
lock.lock();
bool isRunning = this->isRunning;
lock.unlock();
return isRunning;
}
这是一个简单的程序,看它是否有效:
void Tick(){ cout << "TICK" << endl; }
int main() {
Timer timer(milliseconds(1000), Tick);
timer.Start();
cin.get();
}
当我使用g ++构建应用程序时,该程序可以构建并运行,没有任何问题。但是,当我使用Microsoft的编译器(v18)时,程序也会进行编译,但是在运行时会失败。
当我使用发布配置时,从其中一个线程得到以下异常:
Program.exe中0x000007F8D8E14A30(msvcr120.dll)的未处理异常:请求致命程序退出。
当我使用调试配置时,每秒都会弹出一个Microsoft Visual C ++运行时库错误:
调试错误!
程式:... \ path \ Program.exe
R6010-已调用abort()
在两种配置中:
引发异常/错误开始在计时器循环的第二次迭代中弹出。
Tick
即使thread(handler)
被调用,该程序也不会进入函数。
尽管错误跟踪时的堆栈跟踪在这两种配置中有所不同,但是它们都不包含我的代码中的任何内容。都以ntdll.dll!UserThreadStart()
; 调试结束msvcr123d.dll!_NMSG_WRITE()
于发行版本结束msvcr120.dll!abort()
。
为什么会出现问题,为什么只有在使用MSVC编译应用程序后才出现问题?这是某种MSVC的错误吗?还是应该更改编译器配置中的某些内容?
您的线程正在抛出std::bad_function_call
,未处理异常,因此正在调用运行时abort()
。
变更:
const std::function<void()>& handler;
至
const std::function<void()> handler;
解决问题。我猜这是因为您在线程之间共享它?
如果创建本地并传递对该本地的引用,则也可以使用:
const std::function<void()> f = Tick;
Timer timer(std::chrono::milliseconds(1000), f);
因此,它一定超出了范围。
编辑:实际上,函数对象在ctor调用后被销毁了。不知道为什么会这样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句