Question

I was looking into libstdc++ code and was surprised that it sets the badbit on a stream when an operator>> or operator<< is interupted by a cancellation point of pthread (which, if I understand correctly, is implemented by throwing a special magic exception object).

Apparently, the C++ Standard requires that an exception escaping to the respective I/O function shall set the badbit. But to my understanding, a pthread cancellation isn't needed to be considered an "exception" in the C++ sense.

Does that mean that when calling pthread_cancel'ing a thread that uses cout and friends, one always has to clear the badbit after the thread doing the I/O exited (to be sure just in case the thread caused the badbit to be set)?

Was it helpful?

Solution

The C++ standard doesn't specify any specific behavior for pthread's special exception. However, it specifies that catching any exception results in setting std::ios_base::badbit. The standard would need to be augmented to handle special exceptions special. The interactions between different standards doing things independent from the C++ in the C++ standard are clearly outside the C++ standard.

At one Kona meeting (~2006/2007) cancelling threads via exceptions was discussed at length. It was determined that supporting thread cancellation causes weird problem and that there were too many questions open to support thread cancellation in C++. If you want working thread cancallation support in C++ you'll need to get it integrated with the C++ standard. I wouldn't expect large support for thread cancellation in C++, though.

For more practical matters I can also imagine that throwing from, e.g., read(2) may leave the stream of an unsuspecting I/O stream implementation in an inconsistent state! System functions didn't use to throw. If the start doing so funny things may happen. That is, the stabdard library would need to be aware of this change to the system call behavior. This silent change in behavior was one of the arguments why thread cancellation via exceptions wasn't considered a viable approach: what applies to the standard C++ library implentation applies even more to user code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top