0

I am trying to create an asynchronous method in C++ using libev. If needed I can pass a callback method as an argument.

For instance

test();
printf("After test() method\n");

the test() is an asynchronous method, so the next printf() statement should be executed before test() completes its execution.

I tried using libev for this simple example :

void testCallback(struct ev_loop *loop, struct ev_io  *watcher, int revents)
{
    sleep(5);
    ev_io_stop(loop, watcher);
}

int test()
{
    struct ev_loop *loop = ev_default_loop(0);
    ev_io watch;

    ev_io_init(&watch, testCallback, 0, EV_READ);
    ev_io_start(loop, &watch);

    ev_run(loop, 0);

    return 0;
}

int main() {
    test();
    printf("After test() method");
    return 0;
}

In this example, the printf is getting executed after that event loop has stopped. Is this kind of functionality possible using libev ? I googled but couldn't get no example with this kind of need.

Chaitanya
  • 3,399
  • 6
  • 29
  • 47

1 Answers1

1

From the code printf should be executed after the loop has stoped. Test is not asynchronus rather the testCallback is asynchronus. You might have misunderstood the logic.

Adnan Akbar
  • 718
  • 6
  • 16
  • Yes, the `printf` gets executed after the loop has stopped. My question is how do I achieve that kind of asynchronous functionality ? Even I dint get this point _Test is not asynchronus rather the testCallback is asynchronus._ Can you be a bit elaborate? – Chaitanya Mar 13 '13 at 05:44
  • ev_run(loop, 0); will not return it is a ever running loop. Move the printf to the callback function and it will be executed before end. Also the ev_io_stop(loop, watcher) causes the loop to end so it is one time event. If you want timer based events see the following http://linux.die.net/man/3/ev – Adnan Akbar Mar 13 '13 at 06:13
  • If I put the printf statement in the callback, it will be executed only after the callback is invoked. I want the printf to executed irrespective of the callback being called. This is what we mean by asynchronous execution right ? – Chaitanya Mar 13 '13 at 06:37
  • asynchronus means it wont block but whenever there is an event( here it means stdin changes ) and the callback will be invoked. – Adnan Akbar Mar 13 '13 at 09:02
  • Yes exactly. But, for me in this case, the test() is blocking. How to avoid that ? – Chaitanya Mar 13 '13 at 10:46
  • When you call something in synchronized way e.g with scanf the program blocks until the input is recieved and then when you get the input you call the function straightaway but with asynch approach you program just comes back and proceed with the next instruction. Your main loop just goes into the loop and whenever there is an event the callback is invoked. The function which will be invoked asynch is testCallback which after sleeping for 5 secs just stops the main loop which at the end calls the printf. – Adnan Akbar Mar 13 '13 at 12:29