小编Sys*_*dev的帖子

带有std :: thread和std :: chrono的基本计时器

我正在尝试使用经典方法实现基本计时器:start()和stop().我正在使用带有std :: thread和std :: chrono的c ++ 11.

  • 启动方法.创建一个在给定间隔时间内处于睡眠状态的新线程,然后执行给定的std :: function.当'running'标志为真时,重复此过程.
  • 停止方法.只需将'running'标志设置为false即可.

我创建并启动了一个显示"Hello!"的Timer对象.每一秒,然后与其他线程我试图停止计时器,但我不能.计时器永不停止.

我认为问题在于th.join()[*]在线程完成之前停止执行,但是当我删除th.join()行时,程序显然在计时器开始计数之前完成.

所以,我的问题是如何在不停止其他线程的情况下运行线程?

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

class Timer
{
    thread th;
    bool running = false;

public:
    typedef std::chrono::milliseconds Interval;
    typedef std::function<void(void)> Timeout;

    void start(const Interval &interval,
               const Timeout &timeout)
    {
        running = true;

        th = thread([=]()
        {
            while (running == true) {
                this_thread::sleep_for(interval);
                timeout();
            }
        });

// [*]
        th.join();
    }

    void stop()
    {
        running = false;
    }
};

int main(void)
{
    Timer tHello; …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading timer c++11

8
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

c++11 ×1

multithreading ×1

timer ×1