views:

223

answers:

3

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?

A: 

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.

Marty Fried
Yeah! This is what I'm trying to do.
bobobobo
+2  A: 

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.

avakar
Ah, good point about `CreateWaitableTimer`
bobobobo
+1  A: 

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() ;
Thomas
And you sir, have answered the question! ty.
bobobobo
Mr.Ree
Both good points.
Thomas