[ECOS] pthread_mutex_unlock when mutex is not locked

Nick Garnett nickg@ecoscentric.com
Thu Apr 28 10:15:00 GMT 2005

Rubén Pérez de Aranda Alonso <rperez@sidsa.es> writes:

> Ok,
> I understand you explain me. The standard also defines that a mutex
> locked by a thread must be unlocked by the same thread. However,
> many implementations of Pthreads allow use the mutex to signal events
> carring out lock and unlock of the mutex from different threads.

Such implementation are broken in that case. It is not even clear how
such an implementation could handle priority inheritance correctly.

> But, ok, the DSR is not a thread :-).
> An example is the next code, that works with the POSIX compat layer
> of eCOS.
> N threads are created and executed in differents priority
> levels each one of them in SCHED_FIFO policy. The thread th(K)
> takes the priority equal to K and locks the pre-locked mutex
> m((K-1)%N).
> The th(K) also unlocks the mutex m(K) where the th(K+1) is
> waiting. So, because the Prio(th(K+1)) > Prio(th(K)) then the
> th(K+1) is dispatched at the same time that the th(K) unlocks
> the mutex m(K).

Sorry, but this program totally violates the intended and documented
way in which mutexes should be used.

> Anothe cuestion. Can I use the next code to guaratee the mutual
> exclusion in access to critical data from a thread and a DSR?
> DSR ()
> {
>   if (pthread_mutex_trylock(&mutex) == 0)
>   {
>     // Access to data
>     // Calculate .....
>      // Unlock
>     pthread_mutex_unlock(&mutex);
>   }
> }

That is not guaranteed to work. Posix threads have additional data
attached to them, which is absent in non-Posix threads. Any
Posix functions called in a DSR may try to access this extra data. If
it is not a Posix thread then the access will fail, or attempt to
access invalid memory.

ISRs and DSRs are not part of the Posix secification, any attempt to
use Posix calls in these contexts in undefined. Instead you should be
using the eCos API, specifically the cyg_drv_* routines defined in the
driver API.

Nick Garnett                                     eCos Kernel Architect
http://www.ecoscentric.com                The eCos and RedBoot experts

Before posting, please read the FAQ: http://ecos.sourceware.org/fom/ecos
and search the list archive: http://ecos.sourceware.org/ml/ecos-discuss

More information about the Ecos-discuss mailing list