如何使用 C++ 11 创建计时器事件?

2023-12-07

如何使用 C++ 11 创建计时器事件?

我需要这样的东西:“从现在起 1 秒后给我打电话”。

有图书馆吗?


做了一个简单的实现,我相信这是你想要实现的目标。您可以使用该类later具有以下参数:

  • int(等待运行代码的毫秒数)
  • bool(如果为 true,则立即返回并在指定时间后在另一个线程上运行代码)
  • 可变参数(正是您要提供的内容)std::绑定)

你可以改变std::chrono::milliseconds to std::chrono::nanoseconds or microseconds为了获得更高的精度,请添加第二个 int 和 for 循环来指定运行代码的次数。

来吧,享受吧:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }

};

void test1(void)
{
    return;
}

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;
}

两秒后输出:

101
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 C++ 11 创建计时器事件? 的相关文章

随机推荐