[LC++]Question on pthreads

Carlo Wood carlo at alinoe.com
Thu Jul 15 16:34:01 UTC 2004


On Wed, Jul 14, 2004 at 04:33:59PM -0700, Krishna Monian wrote:
> > However I think the spawned thread can close the
> > application (if the
> > unexpected condition occurs) just by calling
> > exit(1).
>  
> Even I thought exit(1) would exit the process. But
> this doesn't seem to be happening. Is there any other
> call that can terminate the process?

There is no way to cleanly exit because other threads
might be waiting for locks.  The only way in that case
is to abruptly just stop everything with a signal.
You can try abort() (or better: std::terminate(), which
will call abort()).  This will cause a core dump however.
If you don't want that, then try raise(9);

Actually - you might have a chance by calling _Exit(1);
Note the underscore.  But I am not 100% sure in that case.

This is how libcwd (http://libcwd.sourceforge.net) terminates
a process cleanly in the case of a fatal error:

  {
    int __libcwd_oldstate;
    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &__libcwd_oldstate);

    if (!_private_::mutex_tct<_private_::kill_threads_instance>::trylock())
    {
      // Another thread is already trying to generate a core dump.
      pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
      pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
      pthread_exit(PTHREAD_CANCELED);
    }

    _private_::rwlock_tct<_private_::threadlist_instance>::rdlock(true);
    // Terminate all threads that I know of, so that no locks will remain.
    for(_private_::threadlist_t::iterator thread_iter = _private_::threadlist->begin(); thread_iter != _private_::threadlist->end(); ++thread_iter)
      if (!pthread_equal((*thread_iter).tid, pthread_self()) && (_private_::WST_is_NPTL || (*thread_iter).tid != 1024))
        pthread_cancel((*thread_iter).tid);
    _private_::rwlock_tct<_private_::threadlist_instance>::rdunlock();
     
    pthread_setcancelstate(__libcwd_oldstate, NULL);
  }
  _Exit(254);   // Exit without calling global destructors.

The '_private_::mutex_tct' and '_private_::rwlock_tct' are still libcwd specific
things - the latter is a read/write lock! - it is a lock for the critical area
garding '_private_::threadlist'.  I don't think it is feasible however to
create a list of threads yourself this way.   My conclusion*) is that locks
*will* remain when calling _Exit() and therefore deadlocks might occurs(?).

-- 
Carlo Wood <carlo at alinoe.com>

*) That might seem weird cause I am the author of libcwd - but hey, I have
   a bad memory ;).




More information about the tuxCPProgramming mailing list