多线程用c语言编译有错,c – 使用MSVC编译的多线程应用程序在运行时失败

我已经实现了一个循环运行提供的函数的类.

//Timer.h

#include

#include

#include

class Timer {

public:

Timer(const std::chrono::milliseconds period, const std::function& handler);

~Timer();

void Start();

void Stop();

bool IsRunning() const;

private:

const std::function& 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& 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)时,程序也会编译,但它在运行时会失败.

当我使用发布配置时,我从其中一个线程获得以下异常:

Unhandled exception at 0x000007F8D8E14A30 (msvcr120.dll) in Program.exe: Fatal program exit requested.

当我使用调试配置时,每秒会弹出一次Microsoft Visual C运行时库错误:

Debug Error!

Program: …\path\Program.exe

R6010

– abort() has been called

在两种配置中:

>抛出异常/错误在计时器循环的第二次迭代中开始弹出.

>即使调用了线程(处理程序),程序也不会进入Tick函数.

>虽然错误时刻的堆栈跟踪在这两种配置中有所不同,但它们都不包含我的代码中的任何内容.两者都以ntdll.dll开头!UserThreadStart();调试以msvcr123d.dll!_NMSG_WRITE()结束,发行版以msvcr120.dll!abort()结束.

为什么只有在使用MSVC编译应用程序时才出现问题?这是某种MSVC的错误吗?或者我应该在编译器的配置中改变一些东西?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值