Handling exception within thread function - c++

I have multithreaded application using C++ (not C++11) using pthread. SO, I have couple of threads running in parallel with corresponding thread functions. In main thread block, I have try-catch block but within thread function, I don't. Each thread function (other than main) runs while(1) loop and breaks when a certain condition is set by main thread indicating to exit. The condition variable check and setting are all done within mutex guards to ensure mutual exclusion. However, within a thread function, some exception occurred and the thread became a zombie and the application crashed. pstack core could not show the stack trace properly, as that might have been corrupted. My question is: should I use try-catch block to handle exception with thread function too? Of course outside the try block should have while(1) block within and catch block should handle the exception gracefully and then probably gracefully end. Can I pass an exception from a child thread passed to the second thread? Ideally not. What should be the best practice?

should I use try-catch block to handle exception with thread function
too?
Yes, because exceptions are a stack-based mechanism. Since each thread has its own stack, it has its own exceptions.
If you have no language support for communicating exceptions, you will have to resort to 'manually' copying the exception obect in the catch and signaling to whatever thread needs to know about it with some inter-thread comms that are specific to your design.

Related

Exit thread within a nested function

I want to check a global bool value in my thread whenever necessary:
If it's true the thread should exit, and the thread should continue if it's false.
While checking, I could be inside a single function or I could be within a nested function. I need to ensure that I return to the main function first, then return 0 in the main function, which seems very stupid.
So the only way I can think of is to throw an exception when the condition is fulfilled and then catch it at the end of this thread, so that all the elements are destructed correctly.
So is there a more standard way in C++ language to do this? How do you exit a thread while you are in a nested function?
Your approach is fine. Compared to the costs of thread creation and destruction, throwing an exception is negligible.
If for some reasons you aren't allowed to use exceptions:
Check that signaling variable several places in your code. Note that regular code runs pretty damn fast so you only need these checks inside/before long calculations (loops) or IO operations that could block. Make sure the rest of the code doesn't depend on the results of some unfinished calculations.
Use a coding style where you always return an error code from every function (at least for this thread).
There are system-specific functions like ExitThread and pthread_exit but they are not recommended to use because they will result in memory leak: destructors will not be called, including CRT/stdlib internal objects if the thread was created using std::thread.
So the answer is: no, there is no standard way to exit a thread in C++. Just consider the thread as a regular function.

Interupt boost thread that is already in condition variable wait call

I'm using the boost interprocess library to create server and client programs for passing opencv mat objects around in shared memory. Each server and client process has two boost threads which are members of a boost::thread_group. One handles command line IO while the other manages data processing. Shared memory access is synchronized using boost::interprocess condition_variables.
Since this program involves shared memory, I need to do some manual cleaning before exiting. My problem is that if the server terminates prematurely, then the processing thread on the client blocks at the wait() call since the server is responsible for sending notifications. I need to somehow interrupt the thread stuck at wait() to initiate shared memory destruction. I understand that calling interrupt() (in my case, thread_group.interrupt_all()) on the thread will cause theboost::thread_interrupted exception to be thrown upon reaching a interruption point (such as wait()), which if left unhandled, would allow the shared memory destruction to proceed. However, when I try to interrupt the thread while it is in wait(), nothing seems to happen. For instance, this prints nothing to the command line:
try {
shared_mat_header->new_data_condition.wait(lock);
} catch (...) {
std::cout << "Thread interrupt occurred\n";
}
I am not at all sure, but it seems like the interrupt() call needs to occur before the thread enters wait() for the exception to be thrown. Is this true? If not, then what is the proper way to interrupt a boost thread that is blocked by a condition_variable.wait() call?
Thanks for any insight.
Edit
I accepted Chris Desjardins' answer, which does not answer the question directly, but has the intended effect. Here I'm translating his code snippet for use with boost::interprocess condition variables, which have slightly different syntax than boost::thread condition variables:
while (_running) {
boost::system_time timeout = boost::get_system_time() + boost::posix_time::milliseconds(1);
if (shared_mat_header->new_data_condition.timed_wait(lock, timeout))
{
//process data
}
}
I prefer to wait with timeouts, then check the return code of the wait call to see if it timed out or not. In fact I have a thread pattern I like to use that resolves this situation (and other common problems with threads in c++).
http://blog.chrisd.info/how-to-run-threads/
The main point for you is to not block infinitely in a thread, so your thread would look like this:
while (_running == true)
{
if (shared_mat_header->new_data_condition.wait_for(lock, boost::chrono::milliseconds(1)) == boost::cv_status::no_timeout)
{
// process data
}
}
Then in your destructor you set _running = false; and join the thread(s).
Try using the "notify function". Keep a pointer to your condition variable and call that instead of interrupting the threads. Interrupting is much more costly than a notify call.
So instead of doing
thread_group.interrupt_all()
call this instead
new_data_condition_pointer->notify_one()

What happens to std::async call if parent/main thread dies

If I am right, the std::async uses a new thread and calls the method in it. I was wondering what happens if the main thread or the parent thread dies. Does the thread controlling the async method dies as well.
There is no concept of a "parent" thread in C++, each thread is independent of the one that it was created by. However, the main thread is special and if it returns from main() or calls exit() then the entire application is terminated even if other threads are still running. Once that happens, the program has undefined behaviour if the still-running threads access any global variables or automatic objects that were on the main thread's stack, or use any standard library objects or call any function not permitted in signal handlers.
In short, do not let other threads run after main completes if you expect sensible results.

Will main() catch exceptions thrown from threads?

I have a pretty large application that dynamically loads shared objects and executes code in the shared object. As a precaution, I put a try/catch around almost everything in main. I created a catch for 3 things: myException (an in house exception), std::exception, and ... (catch all exceptions).
As part of the shared objects execution, many pthreads are created. When a thread throws an exception, it is not caught by main. Is this the standard behavior? How can I catch all exceptions, no matter what thread they are thrown from?
Will main() catch exceptions thrown from threads?
No
When a thread throws an exception, it is not caught by main. Is this the standard behavior?
Yes, this is standard behaviour.
To catch an exception originating in thread X, you have to have the try-catch clause in thread X (for example, around everything in the thread function, similarly to what you already do in main).
For a related question, see How can I propagate exceptions between threads?
Your question is asking for something that isn't conceptually possible.
Try blocks are defined as dynamic constructs of the stack. A try block catches exceptions thrown by code reached dynamically, by call, from its contents.
When you create a new thread, you create a brand-new stack, that is not at all part of the dynamic context of the try block, even if the call to pthread_create is inside the try.
No, main will not catch exceptions thrown from other threads. You would need to use a non-standard, platform specific facility that addresses unhandled exceptions in order to aggregate the handling the way you are describing.
When I build such applications, I make sure each active object has its own top-level exception handling block, precisely to prevent the entire application from exploding if one thread fails. Using a platform-specific catch all I think begs for your overall code / solution to be sloppy. I would not use such a thing.
Consider that throwing an exception unwinds the stack. Each thread has its own stack. You will have to place a try/catch block in each thread function (i.e. in the entry point of each thread).

Efficient exit from multithreaded application (specifics)

I've read a few sources on proper methods of bubbling a message out from a thread to all other threads to exit gracefully (every thread performs it's own exit routine). Of these, I liked the idea of a global atomic boolean that can be flagged from any thread, and all other threads check this flag to perform an exit routine - when all threads are joined, the main thread can then exit the application.
Purely computation threads would probably be handled differently, right?
Is this efficient and safe? Is there a better way to do this?
Thanks!
I'm not a fan of threads checking boolean (or other) status variables to know when to do what, because it's wasteful. The threads would have to spin, constantly checking the variable to see if there are new instructions. This burns the CPU.
A better option is to create a semaphore or in Windows an event, and have all the threads wait on that. The threads can sleep while they arent busy, and wont steal time slices from other threads doing real work simply to check a variable.
In Windows, I use QueueUserAPC to call a function which throws an exception, causing threads to exit cleanly.
I wrote more about the details in this answer here:
How do I guarantee fast shutdown of my win32 app?
In summary, here's what happens:
Say thread A wants to terminate thread B (and then C, D, ...)
Thread A calls QueueUserAPC(), passing the handle to thread B and the address of a function which will throw an Exception of class MyThreadExit.
Thread B runs normally until it calls something that checks for alertable waits. Maybe WaitForSingleObjectEx, maybe SleepEx, or something else.
At this point, thread B runs the APC function passed earlier, causing the exception to be thrown in Thread B.
All stack-allocated objects get automatically destructed correctly as the exception makes thread B 'unwind' its stack.
The outermost thread function of thread B will catch the exception.
Thread B now exits, possibly signalling to Thread A that it's done.