[c++-pthreads] concrete library-code example
Jason Merrill
jason at redhat.com
Thu Dec 25 04:55:59 UTC 2003
On Wed, 24 Dec 2003 09:05:17 -0800, Nathan Myers <ncm at cantrip.org> wrote:
> On Wed, Dec 24, 2003 at 08:09:57AM -0500, Jason Merrill wrote:
>> On Tue, 23 Dec 2003 11:03:14 -0500, Ted Baker <baker at cs.fsu.edu> wrote:
>>
>> > How do you propose to modify read() to throw an exception and
>> > still have backwards compatability with applications that expect
>> > read() to always return (more specifically, to return -1 if it
>> > fails)?
>>
>> read() already doesn't return if it's acting on a cancellation request.
>> Throwing an exception is just a different way of not returning.
>
> Enlarging on this question...
>
> Here is a more-or-less concrete example, for discussion purposes.
> It's meant as a generic example of code written according to the
> existing contract offered by C libraries.
>
> int affect_world(struct state* s)
> {
> int result;
> violate_invariants_or_claim_resources(s);
> result = c_function_or_system_call(s->member);
> if (result < 0) {
> clean_up(s, result);
> return result;
> }
> act_on_result(s, result);
> restore_invariants_and_release_resources(s);
> return 0;
> }
>
> This pattern is extremely common in both C and C++ libraries. If
> read() were to throw (or to "just ... not return"), the program state
> would be corrupted. A redefinition of c_function_or_system_call
> semantics that breaks this code breaks many thousands of existing
> thread-safe C and C++ libraries.
This is not cancellation-safe C under the current POSIX standard, if
c_function_or_system_call is a cancellation point. If it is, cleanups are
run and the thread is terminated. To be truly thread-safe, the user must
use pthread_cleanup_push/pop so that the resources are released on
cancellation.
Implementing cancellation by throwing an exception has no effect on the
thread-safety of this code.
> Jason, do you not consider those libraries worth preserving?
No, they're already broken.
Jason
More information about the c++-pthreads
mailing list