Subject: Re: pthreads since 8/08/03
To: Joerg Sonnenberger <joerg@britannica.bec.de>
From: Nathan J. Williams <nathanw@wasabisystems.com>
List: current-users
Date: 08/15/2003 13:02:30
Joerg Sonnenberger <joerg@britannica.bec.de> writes:

> void status_clear_line()
> {
>   pthread_cleanup_push(unlock_output_lock,NULL);
>   pthread_mutex_lock(&output_lock);
>   clear_line(last_line_len);
>   pthread_mutex_unlock(&output_lock);
>   pthread_cleanup_pop(0);
> }
> 
> IMHO the pthread_mutex_unlock should be dropped and the cleanup
> Handler called, otherwise there is a race between Unlocking
> the mutex and removing the cleanup handler leading to an assertion
> in the pthread code.

The race that you think you see between the pthread_mutex_unlock() and
pthread_cleanup_pop() doesn't exist, because cancellation doesn't
happen at arbitrary points. It only happens at a certain set of
function calls (generally speaking, calls that have the potential to
wait for a long time on external events), and pthread_mutex_unlock()
is not such a cancellation point.

It's a matter of style, not correctness, as to whether one should
write code in the above manner or by calling pthread_cleanup_pop(1).

> we have another race: if the thread is cancelled after PTQ_REMOVE
> but before the call to the cleanup handler, the mutex is still
> locked.

A similar argument applies. There aren't any cancellation points in
this path, so there's no race.

        - Nathan