相当于 C++ 的 window.setTimeout()

发布于 2024-08-25 17:43:22 字数 947 浏览 8 评论 0原文

在 javascript 中,有一个非常非常好的函数 window.setTimeout( func, 1000 ) ;,它将在 1000 毫秒后异步调用 func

我想在 C++ 中做类似的事情(没有多线程),所以我组合了一个示例循环,例如:

    #include <stdio.h>

    struct Callback
    {
      // The _time_ this function will be executed.
      double execTime ;

      // The function to execute after execTime has passed
      void* func ;
    } ;

    // Sample function to execute
    void go()
    {
      puts( "GO" ) ;
    }

    // Global program-wide sense of time
    double time ;

    int main()
    {
      // start the timer
      time = 0 ;

      // Make a sample callback
      Callback c1 ;
      c1.execTime = 10000 ;
      c1.func = go ;

      while( 1 )
      {
        // its time to execute it
        if( time > c1.execTime )
        {
          c1.func ; // !! doesn't work!
        }

        time++;
      }
    }

我怎样才能使这样的事情工作?

In javascript there's this sweet, sweet function window.setTimeout( func, 1000 ) ; which will asynchronously invoke func after 1000 ms.

I want to do something similar in C++ (without multithreading), so I put together a sample loop like:

    #include <stdio.h>

    struct Callback
    {
      // The _time_ this function will be executed.
      double execTime ;

      // The function to execute after execTime has passed
      void* func ;
    } ;

    // Sample function to execute
    void go()
    {
      puts( "GO" ) ;
    }

    // Global program-wide sense of time
    double time ;

    int main()
    {
      // start the timer
      time = 0 ;

      // Make a sample callback
      Callback c1 ;
      c1.execTime = 10000 ;
      c1.func = go ;

      while( 1 )
      {
        // its time to execute it
        if( time > c1.execTime )
        {
          c1.func ; // !! doesn't work!
        }

        time++;
      }
    }

How can I make something like this work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

北陌 2024-09-01 17:43:22

C++11出来后,如果你使用的是c++11支持的编译器,你可以使用lambda可变参数模板函数异步线程 strong> 轻松地用 C++ 模拟 javascript 函数。

这是我为 setTimeOut 编写的代码,它经过了充分测试:

setTimeOut 函数的定义:

    #include <windows.h>//different header file in linux
    #include <future>
    using namespace std;

    template <typename... ParamTypes>
    void setTimeOut(int milliseconds,std::function<void(ParamTypes...)> func,ParamTypes... parames)
    {   
        std::async(std::launch::async,[=]()
        {       
            Sleep(milliseconds);
            func(parames...); 
        });
     };

此函数通过使用 c+11 的可变参数模板接受变量参数,
代码可以告诉你如何使用它:

    #include <iostream>
    #include <thread>
    #include <string>
    #include <functional>
    #include <windows.h>

    #include <future>
    using namespace std;
    int main() 
    {
        std::mutex locker;
        std::function<void()> func1 = [&]()
        {
            std::unique_lock<std::mutex> lk(locker);
            std::cout << "func 1 is trigged:" << "   no parameter" << std::endl;
            lk.unlock();
        };      
        std::function<void(int)> func2 = [&](int param)
        {
            std::unique_lock<std::mutex> lk(locker);
            std::cout << "func 2 is trigged:" << "   int: " << param <<std::endl;
            lk.unlock();
        };
        std::function<void(int,std::string)> func3 = [&](int param1,std::string param2)
        {
            std::unique_lock<std::mutex> lk(locker);
            std::cout << "func 3 is trigged:" << "   int: " << param1 << ";  string: " << param2 << std::endl;
            lk.unlock();
        };

        for(int index=0;index<100;index++)
        {
            std::unique_lock<std::mutex> lk1(locker);
            std::cout << "set timer for func  1" << std::endl;
            lk1.unlock();
            setTimeOut<>(1000,func1);

            std::unique_lock<std::mutex> lk2(locker);
            std::cout << "set timer for func  2" << std::endl;
            lk2.unlock();
            setTimeOut<int>(2000,func2,10000);

            std::unique_lock<std::mutex> lk3(locker);
            std::cout << "set timer for func  3" << std::endl;
            lk3.unlock();
            setTimeOut<int,std::string>(5000,func3,10000,"ddddd");
        }
        Sleep(10000000);
    }

After C++11 came out, and if your are using c++11 supported compiler, you can use lambda, variadic template function and asynchronous thread to simulate javascript function in c++ easily.

Here is the code I wrote for setTimeOut, it is fully tested:

setTimeOut funtion's definition:

    #include <windows.h>//different header file in linux
    #include <future>
    using namespace std;

    template <typename... ParamTypes>
    void setTimeOut(int milliseconds,std::function<void(ParamTypes...)> func,ParamTypes... parames)
    {   
        std::async(std::launch::async,[=]()
        {       
            Sleep(milliseconds);
            func(parames...); 
        });
     };

This function accepts variable arguments by using c+11's variadic template,
The code can show you how to use it:

    #include <iostream>
    #include <thread>
    #include <string>
    #include <functional>
    #include <windows.h>

    #include <future>
    using namespace std;
    int main() 
    {
        std::mutex locker;
        std::function<void()> func1 = [&]()
        {
            std::unique_lock<std::mutex> lk(locker);
            std::cout << "func 1 is trigged:" << "   no parameter" << std::endl;
            lk.unlock();
        };      
        std::function<void(int)> func2 = [&](int param)
        {
            std::unique_lock<std::mutex> lk(locker);
            std::cout << "func 2 is trigged:" << "   int: " << param <<std::endl;
            lk.unlock();
        };
        std::function<void(int,std::string)> func3 = [&](int param1,std::string param2)
        {
            std::unique_lock<std::mutex> lk(locker);
            std::cout << "func 3 is trigged:" << "   int: " << param1 << ";  string: " << param2 << std::endl;
            lk.unlock();
        };

        for(int index=0;index<100;index++)
        {
            std::unique_lock<std::mutex> lk1(locker);
            std::cout << "set timer for func  1" << std::endl;
            lk1.unlock();
            setTimeOut<>(1000,func1);

            std::unique_lock<std::mutex> lk2(locker);
            std::cout << "set timer for func  2" << std::endl;
            lk2.unlock();
            setTimeOut<int>(2000,func2,10000);

            std::unique_lock<std::mutex> lk3(locker);
            std::cout << "set timer for func  3" << std::endl;
            lk3.unlock();
            setTimeOut<int,std::string>(5000,func3,10000,"ddddd");
        }
        Sleep(10000000);
    }
梦里人 2024-09-01 17:43:22

Callback::func 设为 void (*)() 类型,即

struct Callback
{
    double execTime;
    void (*func)();
};

您可以这样调用该函数:

c1.func();

另外,不要忙等待。在 Linux 上使用 ualarmCreateWaitableTimer

Make Callback::func of type void (*)(), i.e.

struct Callback
{
    double execTime;
    void (*func)();
};

You can call the function this way:

c1.func();

Also, don't busy-wait. Use ualarm on Linux or CreateWaitableTimer on Windows.

鯉魚旗 2024-09-01 17:43:22

就 C++ 本身而言,您的能力非常有限。您需要一个多线程操作系统,您可以在其中使用睡眠功能(您仍然可以让程序使用单独的线程继续运行),或者您需要一个消息系统,例如 Windows。

我认为你可以做某事的唯一另一种方法是在代码中分散大量调用,这些调用调用返回 true 或 false 的函数,具体取决于时间是否已过。当然,该函数可以是回调,但您仍然需要定期调用它。

In C++ by itself, you're pretty limited. You need either a multithreaded OS, where you could use a sleep function (you can still have the program continue running with a separate thread), or you need a messaging system, like Windows.

The only other way I see that you can do something is to have a lot of calls scattered throughout the code that calls a function that returns true or false, depending on whether the time has elapsed. The function could, of course, be a callback, but you would still need to call it periodically.

神魇的王 2024-09-01 17:43:22

我只是在这里修复你的代码,而不是跳出框框思考。其他答案已经对此给出了一些指示。

为了更好的类型安全,您应该按如下方式声明回调指针:

  // The function to execute after execTime has passed
  void (*func)() ;

然后,将其调用为:

  c1.func() ;

I'm only fixing your code here, not thinking outside the box. The other answers already gave some pointers for that.

For better type safety, you should declare your callback pointer as follows:

  // The function to execute after execTime has passed
  void (*func)() ;

Then, call it as:

  c1.func() ;
怀中猫帐中妖 2024-09-01 17:43:22

另一个(更好的)答案是在 C++ 中使用 标头,并像这样声明函数:

#include <functional>

function<void ()> func ;

// assign like
func = go ; //go is a function name that accepts 0 parameters
// and has return type void

// exec like
func() ;

Another (better) answer would be to use the <functional> header in C++, and declare the function like so:

#include <functional>

function<void ()> func ;

// assign like
func = go ; //go is a function name that accepts 0 parameters
// and has return type void

// exec like
func() ;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文