[fpc-pascal] Semaphore problems

Vinzent Hoefler JeLlyFish.software at gmx.net
Tue Jul 25 09:30:50 CEST 2006

On Tuesday 25 July 2006 06:40, Micha Nelissen wrote:
> Vinzent Höfler wrote:
> > because we assume it's non-recursive, that was the whole point. So
> > we should *first* check the count and then may lock/unlock the
> > mutex accordingly.
> Note that these two actions must be atomic.

Oh, really?

> This is what the TryLock is for.

No, that's what the "Owner_Check_Lock" in my posted code would be for in 
the first place. But you're right, TryLock makes it possibly easier to 
detect/handle failures.

So the code from 

>    // Now try locking the real mutex.

should actually be more like:

|    // First encounter? So lock it actually.
|    if self.Count = 0 then
|    begin
|       // This  should  *always*  succeed,  because  we're  the owning
|       // thread (we've just checked it, right?) and we didn't lock it
|       // yet according to "Count".
|       // Thinkable  ways  how this can fail is if somebody has direct
|       // access  to  the  actual  pthread  mutex  inside  here  or we
|       // fuc^Wmessed up the counter somehow ...
|       if pthread_mutex_trylock (self...) <> 0 then
|          // Our real mutex couldn't be locked!? This *is* strange.
|          exit (FAILURE);
|    end {if};
|    // Alright, we got it. Mutex is locked (or at least, it *should* be
|    // already), so count up.
|    self.Count := self.Count + 1;
|    self.Owner_Check.Unlock;
|    exit (SUCCESS);
A pthread_mutex_trylock alone wouldn't actually help on a non-recursive 
"real" mutex. Because: if it's already locked I still don't know if it 
belongs to the current thread, but precisely that knowledge is needed 
to implement the recursive one on top of a non-recursive.


More information about the fpc-pascal mailing list