0

In a typical ASIO or event-based programming library like libevent, is there a way to set a deadline for each callback?

I am worried about possible infinite loops within the callbacks. Is there a way to gracefully detect them, remove the misbehaving callback from task queue and continue processing other tasks in the queue?

I can think of a way to detect it through an external thread and kill the event-loop thread and create a different thread but I am trying to see if there are any other commonly used methods. I believe this is a problem which someone has faced at some point of time and thought through a solution

Swaroop
  • 91
  • 4
  • I'm not sure I understand what problem you're trying to solve. What do you mean by "within the callbacks"? Do you mean that a callback function might never return? If so, presumably that's because it's doing useful work, right? – David Schwartz Dec 24 '12 at 12:40
  • Thanks for the comment.. Yes.. I am facing scenarios where I call a function from a library which is a blackbox to me inside a event handler registered with libevent's event_base and it never returns. In all probabilities it is a bug inside the library. I am looking for a recovery mechanism. I was wondering that it makes sense for an event handler library to provide a way to set deadline for each event it handles, but I haven't been able yo think through how such a thing can be implemented.. – Swaroop Dec 25 '12 at 04:03
  • You can't fix a bug without know what the bug is, sorry. You'll have to isolate the buggy code into its own process. – David Schwartz Dec 25 '12 at 04:04

1 Answers1

1

There is no general way to unstick a thread without its cooperation, whether it's running a callback or not. The thread may hold critical locks or may have acquired resources that would never get released if the thread was somehow coerced to stop from the outside.

If you really do need this functionality, then all code that could potentially be interrupted must be designed to support some specific method of interruption. You can start a deadline timer when you enter the callback and cancel it when you're finished. The deadline timer would have to trigger the thread's interruption mechanism. You'd need at least one other thread running the I/O service in order for some thread to run the timer handler while the callback was running in another thread.

You can also isolate the code in its own process with some kind of wrapper. Then if the code fails to terminate, you can kill the process from the outside.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278