This is the mail archive of the
mailing list for the pthreas-win32 project.
RE: problem using pthread_cancel and pthread_mutex_lock
- From: Simon Gerblich <sgerblich at daronmont dot com dot au>
- To: vc <vcotirlea1 at hotmail dot com>
- Cc: pthreads-win32 at sources dot redhat dot com
- Date: Tue, 24 Feb 2004 14:53:34 +1030
- Subject: RE: problem using pthread_cancel and pthread_mutex_lock
>So, my question is: how can a thread cleanly cancel another thread
>which is waiting in a 'pthread_mutex_lock' call, so that this mutex is
>available again ?
I can see a few problems in what you are doing.
A mutex is not really designed to be locked in a thread for a long time and
unlocked by another thread. When I use a mutex in a thread I lock it - do
what I have to do - and then unlock it ASAP. I don't use mutexes to
synchronise threads. I use them to protect data. Pthread mutexes are not
I use deferred cancellation instead of asynchronous cancellation because of
recommendations in "Programming with POSIX Threads" by David Butenhof.
Page 150 "Avoid asynchronous cancellation. It is difficult to use correctly
and is rarely useful."
Page 151 "Asynchronous cancellation can occur at any hardware instruction.
On some computers it may even be possible to interrupt some instructions in
the middle. That makes it really difficult to determine what the canceled
thread was doing."
Page 151 "Call no code with asynchronous cancellation enabled unless you
wrote it to be async-cancel safe - and even then, think twice!"
I write my applications with deferred cancellation and the threads blocking
on message queues, which are cancellation points. When a cancel is
requested the threads exit cleanly when they next go to read the message
queue. I have minimal cancellation points in my code so that I know exactly
where my threads will cancel.
Without knowing exactly what you are trying to do I think you should have a
look at using a condition variable instead of a mutex for your thread
syncing. Waiting on a condition variable is a cancellation point.
Be aware that the Sleep() function on windows is not a cancellation point.
I have written my own sleep functions to use with pthreads-win32 that waits
on condition variables with timeouts.
If your not lurking in the google groups comp.programming.threads I'd
recommend it. I've learnt a lot following threads on pthreads, etc.