【问题标题】:c++ timer terminate without an active exception?c ++计时器在没有活动异常的情况下终止?
【发布时间】:2021-10-10 01:25:07
【问题描述】:

我想在 C++ 中设计一个计时器,在固定时间后执行我的功能。

代码喜欢这样:

#include <thread>
typedef void (*callback)();
class timer {
 public:
   void start(int sec, callback f) {
     std::thread t([&sec, &f]() {sleep(sec); f();});
   }
};

void test () {
  printf("here called\n");
}
int main() {
  timer t;
  t.start(3, test);
  while (1);
}

但是当我运行这段代码时,我得到了:

terminate called without an active exception
[1]    3168208 abort (core dumped)  ./a.out

你能帮忙吗?并且,对于更灵活的计时器设计有什么建议吗?

【问题讨论】:

  • sleep 纯粹是特定于平台的。我想你在找:std::this_thread::sleep_for(std::chrono::seconds(sec));(包括&lt;chrono&gt;
  • 此外,您还有一个问题,t 通过引用捕获 seccallback,但这些是对 start 本地变量的引用,其生命周期在 start 返回时立即结束.

标签: c++ multithreading c++11


【解决方案1】:

您创建了一个 std::thread 并在没有分离的情况下将其销毁。

std::thread t([&sec, &f]() {sleep(sec);

要么拨打join等待,要么拨打detach

还要注意 cmets 中的引用捕获问题。

【讨论】:

【解决方案2】:

您的代码有一些问题需要解决:

  1. 生成std::thread 后,您需要使用std::thread::join() 对其进行同步。
  2. sec 参数中删除引用捕获,以防止dangling of referencesstart() 范围的末尾。
  3. sleep() 依赖于平台,因此您的代码仅适用于支持它的某些平台。而是使用 std::this_thread::sleep_for(std::chrono::seconds(sec));
#include <thread>
#include <chrono> // For std::chrono
#include <cstdio> // For printf

typedef void (*callback)();

class timer {
    // Bring the thread object outside the function and make it an instance variable of the class
    std::thread t;
public:
    // Spawns a thread
    void start(int const sec, callback&& f) {
        if (t.joinable()) // If the object already has a thread attached to it, call 'join()' on it
            t.join();
        /* Capture 'sec' by value as it is a local variable, consequently, capture
          'f' by reference as it is a function and its lifetime is throughout the whole
          program */
        t = std::thread([sec, &f]() {
                std::this_thread::sleep_for(std::chrono::seconds(sec));
                f();
            });
    }
    // After the class gets destroyed, the thread is synchronized
    ~timer() {
        t.join();
    }
};

void test () {
    printf("here called\n");
}

int main() {
    timer t;
    t.start(3, test);
}

【讨论】:

    猜你喜欢
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2011-09-09
    • 2021-07-02
    • 2014-10-14
    • 1970-01-01
    相关资源
    最近更新 更多