Search code examples
csetjmp

C setjmp.h and ucontext.h, which is better?


Hi I'm need to jump from a place to another...

But I would like to know which is better to use, setjmp or ucontext, things like:

  • Are setjmp and ucontext portable?
  • My code is thread safe using these library?
  • Why use one instead another?
  • Which is fast and secure?
  • ...(Someone please, can answer future question that I forgot to put here?)

Please give a little more information that I'm asking for, like examples or some docs...

I had searching on the web, but I only got exception handling in C like example of setjmp, and I got nothing about ucontex.h, I got that it was used for multitask, what's the difference of it and pthread?

Thanks a lot.


Solution

  • setjmp is portable (ISO C89 and C99) and ucontext (obsolescent in SUSv3 and removed from SUSv4/POSIX 2008) is not. However ucontext was considerably more powerful in specification. In practice, if you used nasty hacks with setjmp/longjmp and signal handlers and alternate signal handling stacks, you could make these just about as powerful as ucontext, but they were not "portable".

    Neither should be used for multithreading. For that purpose POSIX threads (pthread functions). I have several reasons for saying this:

    • If you're writing threaded code, you might as well make it actually run concurrently. We're hitting the speed limits of non-parallel computing and future machines will be more and more parallel, so take advantage of that.
    • ucontext was removed from the standards and might not be supported in future OS's (or even some present ones?)
    • Rolling your own threads cannot be made transparent to library code you might want to use. It might break library code that makes reasonable assumptions about concurrency, locking, etc. As long as your multithreading is cooperative rather than async-signal-based there are probably not too many issues like this, but once you've gotten this deep into nonportable hacks things can get very fragile.
    • ...and probably some more reasons I can't think of right now. :-)