[Help-gnutls] Thread cancellation

Scott Lamb slamb at slamb.org
Thu Dec 18 16:32:46 CET 2003


Hello,

I stumbled onto gnutls through the dmoz/google directory link. I'm quite 
impressed so far, particularly with the quality of documentation.

I've got a couple questions I didn't see answered, though:

- Is gnutls cancellation-safe?
- Similarly, is it exception-safe?


In case you're not familiar with thread cancellation, here's a quick 
overview:

Thread cancellation is conceptually similar to sending a SIGTERM to a 
process (a termination request) but much safer. Asynchronous 
cancellation happens at any time (difficult to do safely). The more 
normal method is deferred cancellation, where you define cancellation 
points within your code. The system library defines some, too. Most 
blocking operations are cancellation points. You can enable/disable 
cancellation in specific regions of code, or switch between deferred and 
async. There's also a stack of cleanup handlers, roughly corresponding 
to the normal program execution stack. You can push and pop it as you go 
along with pthread_cleanup_(push|pop). It's used for stuff like this, 
which safely locks and unlocks a mutex:

     pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
     pthread_mutex_lock(&mut);
     /* do some work */
     pthread_cleanup_pop(1);

So I think cancellation safety essentially boils down to not leaking 
resources or being in an inconsistent state whenever in a cancellation 
point. There's a list of the system ones at 
<http://www.opengroup.org/onlinepubs/007904975/functions/xsh_chap02_09.html>). 
But no holding locks or holding dynamically-allocated stuff on the stack 
unless you've explicitly defined a cleanup to deal with it.

Plus to be friendly to cancellation, any long-running arithmetic 
operations should either do pthread_testcancel() periodically or 
(carefully!) enable asynchronous cancellation.


Exception safety is pretty similar. I'd be thrilled if I could define a 
new transport layer and throw C++ exceptions all the way through the 
gnutls code to my code on the other side. If the transport operations 
are considered cancellation points (without using pthread_cleanup_xxx), 
it's exception-safe. (Provided that I compile with -fexceptions, but 
that's easy.) It'd save me the trouble of converting my exceptions to 
C-friendly errors and back again.

(In fact, these are so similar that the pthread standards people 
suggested that cancellations be implemented with exceptions in C++, so 
try/catch blocks work with cancellation as an alternative to 
pthread_cleanup_xxx(). In a couple of newer systems (Tru64 and Linux 
with an extremely new glibc as in Fedora), they are. Most good C++ code 
is already exception-safe, so thread cancellation is extremely practical 
under C++.)


Thanks,
Scott Lamb






More information about the Gnutls-help mailing list