且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-17 16:18:52

对我认为想要的东西进行了简单的实现达到。您可以使用带有以下参数的类以后

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:


  • int(毫秒等待直到运行代码)

  • bool(如果为true,它会立即返回并在指定时间后在另一个线程上运行代码)

  • 可变参数(正是您要输入的内容 std :: bind

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

您可以将 std :: chrono :: milliseconds 更改为 std :: chrono :: nanoseconds microseconds 获得更高的精度,并添加第二个int和for循环来指定

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

在这里,请享受:

#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