Libasync tutorial

Lesson 1: Hello, World!

Prev Index Next

OK. Let's dive right in.

examples/helloworld.C

 1:   #include "async.h"
 2:   
 3:   void
 4:   doprint()
 5:   {
 6:     warn << "Hello," << " World!\n";
 7:     exit(0);
 8:   }
 9:   
10:   int
11:   main(int argc, char *argv[])
12:   {
13:     async_init();
14:     delaycb(5, 0, wrap(doprint));
15:     amain();
16:   }

All examples in this tutorial are accessible in the examples/ directory. Use the supplied Makefile to build.

There are several things going on in this program. First, a program using libasync should call async_init() before doing anything else; it initializes a bunch of things. Secondly, the last statement of main() is typically amain(). This puts the program in an event-loop. Only an explicit call to exit() will stop the program.

Notice the use of warn in function doprint. It is the libasync equivalent of cerr in C++ or fprintf(stderr, "...") in C. You will see more examples of warn throughout this tutorial. (You can also use fatal. This also prints out a message but exits afterward.)

The most interesting part of this program is the delaycb() function call. Delaycb takes 3 arguments: seconds, nanoseconds, and a callback. After the specified amount of time, the callback function is invoked. In this case the callback function is wrap(doprint). (Function doprint is not invoked on line 14!) Wrap is a very clever mechanism to specify callback functions, but in this case not much clever stuff is going on. We simply pass the function (doprint) that we would like to have called when the 5 seconds pass. 5 seconds after calling delaycb, the alarm goes off and the underlying system calls doprint, as promised.

Unsurprisingly, this program sleeps for 5 seconds, prints out "Hello, World!", and exits.

You can turn off delayed callbacks using timecb_remove.

examples/nocall.C

 1:   #include "async.h"
 2:   
 3:   void
 4:   doprint()
 5:   {
 6:     warn << "Hello," << " World!\n";
 7:     exit(0);
 8:   }
 9:   
10:   int
11:   main(int argc, char *argv[])
12:   {
13:     async_init();
14:     timecb_t *foo = delaycb(5, 0, wrap(doprint));
15:     timecb_remove(foo);
16:     delaycb(10, 0, wrap(doprint));
17:     amain();
18:   }

The timecb_remove call on line 15 cancels the delaycb call on line 14. After 10 seconds this program prints "Hello, World!" and exits. This is because of the delaycb call on line 16.

Note that you can only cancel a certain callback with timecb_remove once. Calling timecb_remove on the same timecb_t* twice will cause your program to crash. Also, you cannot call timecb_remove once the callback has been invoked after the specified amount of time.

Lesson 2 explains how to set callbacks to object methods.

Prev Index Next

Back to main.