c++asynchronoussleepusleep

Alternate ways to delay my program without sleeping because of the use of asynchronous IO in C++?


I have a questions regarding alternate ways to delay a program in C++ besides sleeping.

I have a part of my program that receives and sends UDP packets to a controller. This part of the program has to run asynchronously. In order to reduce the overhead of this provider I decided to use asynchronous IO to receive the UDP packets rather than having a separate thread monitor the socket.

I followed this example of a sigaction to accomplish this. I noticed that if I try to use usleep while this sigaction is active it will break my sleep whenever I receive a packet. This kind of makes sense since I assume the sigaction is triggered by some sort of interrupt on the CPU which might stop the CPU from sleeping. If anyone has a good explanation for why this happens I would be curious to know. My issues is that there are times where I have to send several packets in succession and need to make sure to delay them otherwise they are missed by my controller.

I usually would use a sleep to delay the sending of the packets, but now I can't because of it gets broken by my sigaction. I have thought about maybe using a busy wait, but it might be too inconsistent. I have also though about maybe using a queue of packets that is emptied at regular intervals using a timer, but it seems like there might be a simpler solution.

Is there another way to delay the sending of the packets besides sleeping? Is there a way to set up my asynchronous IO so it does not break the sleep? Am I going about this in the wrong way?


Solution

  • Usually when writing an asynchronous program you switch over to an event loop style of programming. Any event system will give you the ability to setup timers which trigger callbacks, using those you can setup schedules for sending traffic and that sort of thing. In addition you typically use them to watch your sockets and simply invoke your callbacks when there is something to be read. While not important for UDP, if you're dealing with TCP at any point you also want to use them to invoke callbacks when sockets are ready to be written to, that way you don't ever block your process while trying to write out data.

    I personally like http://libevent.org/ though I've heard good things of libev as well.