This is the mail archive of the
newlib@sources.redhat.com
mailing list for the newlib project.
Re: Thread safety - reentrancy
- From: "J. Johnston" <jjohnstn at redhat dot com>
- To: Aleksandar Zivkovic <Aleksandar dot Zivkovic at micronasnit dot com>
- Cc: newlib at sources dot redhat dot com
- Date: Wed, 14 Aug 2002 16:34:13 -0400
- Subject: Re: Thread safety - reentrancy
- Organization: Red Hat Inc.
- References: <NCEEICGHENHBAHCNMJPFIEEPCAAA.Aleksandar.Zivkovic@micronasnit.com>
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.