Thread safety - reentrancy
J. Johnston
jjohnstn@redhat.com
Wed Aug 14 13:34:00 GMT 2002
Aleksandar Zivkovic wrote:
>
> Hi, there...
> ------------
>
> Does anyone know if its possible to make newlib thread safe/reentrant,
> without any RTOS support?
> Is there any mechanism to implement e.g.: malloc_lock/malloc_unlock
> without RTOS's functions?
>
> Thanks
> Aleksandar
> ----------
Does your platform have an atomic compare-and-swap operation or something similar
(e.g. cmpxchg on the x86)?
Using such an insn, you can easily create a lock by comparing a memory location with a
"free" value. For the swap-value, you specify the thread-id. If the memory location
has the "free" value, you end up setting it to the thread-id. If not, you end up
reading the value of the current memory location without changing it. You loop until
you have the "free" value which indicates the value was already "free" and a swap has
occurred. If you want to support recursive locking, you can add a second test before looping which checks for the current thread-id already being in
the memory location. You use a
counter to track how many times the current thread has locked. On an unlock, you decrement
the counter. When it reaches 0, you can perform a real unlock by swapping the "free"
value back into the memory location.
-- Jeff J.
More information about the Newlib
mailing list