Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid hung processing in C++ through multithreading

In my code the main loop looks like the following

while ( (data = foo()) != NULL ) {
    // do processing on data here
}

where foo() is written in C (it fetches the next frame in a video stream, using libavcodec, if you're curious).

My problem is that due to reasons too complicated to go in here, sometimes foo() hangs, which stops the whole program. What I want to do is to detect this condition, i.e. foo() is taking more than N seconds and if this is so take action.

I thought of creating a separate thread to run foo() to implement this by I haven't done any multithreaded programming before. Here's what I want to do:

  1. Main thread creates a child thread and which calls foo()
  2. When foo() is done, the child thread returns
  3. Main thread processes data returned by foo()
  4. If the child takes more than a specified number of time an action is taken by the main thread.
  5. Steps 1-4 are repeated as long as foo() doesn't return null, which signals the end.

How do I go about doing this? Do I need three threads (main, to run foo() and for timing)?

Thanks!

like image 673
recipriversexclusion Avatar asked Dec 19 '25 17:12

recipriversexclusion


1 Answers

This is exceedingly difficult to do well. The problem is what you're going to do when foo hangs. Nearly the only thing you can do at that point is abort the program (not just the thread) and start over -- killing the thread and attempting to re-start it might work, but it's dangerous at best. The OS will clean up resources when you kill a process, but not when you kill a single thread. It's essentially impossible to figure out what resources belong exclusively to that thread, and what might be shared with some other thread in the process.

That being the case, perhaps you could move the hanging-prone part to a separate process instead, and kill/restart that process when/if it hangs? You'd then send the data to the parent process via some normal form of IPC (e.g., a pipe). In this case, you could have two threads in the parent (processor and watchdog), or (if available) you could do some sort of asynchronous read with time out, and kill the child when/if the read times out (using only one thread).

like image 52
Jerry Coffin Avatar answered Dec 21 '25 07:12

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!