[coldfire-gnu-discuss] Making malloc threadsafe

Daniel McLean daniel.mclean at optusnet.com.au
Mon Mar 12 08:52:29 UTC 2007


Hi Nathan,

Thanks for the answer.  I had expected them to be declared as weak but 
on checking the newlib code it appears they aren't.  I guess the answer 
I was sort of looking for was whether or not there was the opposite to a 
weak attribute (eg. a strong attribute) which causes a particular 
function to overrule any other one during the link process.. I couldn't 
see this in the docs but am happy enough with my solution at the moment...

As for thread safeness, the RTOS I'm using (FreeRTOS) has functions 
which ensure exclusivity, which I have used for my malloc_lock and 
malloc_unlock routines, so I'm pretty happy that malloc should be 
threadsafe...

Thanks again for the help,

Daniel

Nathan Sidwell wrote:
> Daniel,
>
> newlib's malloc cannot be made thread-safe without writing OS specific 
> code. Namely some kind of semaphore in the malloc_lock/malloc_unlock 
> functions that you found.  You need to replace those.  Simply wrapping 
> all your own calls in equivalent code is insufficient, as newlib uses 
> malloc internally.
>
>> It seems I may have partially solved this problem myself.  If I don't 
>> replace malloc_lock/unlock in one of my own utility libraries that I 
>> link in, but instead implement them in the main.c file it seems to 
>> stop the linker saying that they have been redefined..
>
> Right, this is probably a consequence of the usual linker rules in 
> resolving missing symbols (you don't give a command line, so I cannot 
> be sure).  Namely, all explicitly specified object files are pulled 
> in, then the libraries are searched for remaining missing symbols.  
> Each library is repeatedly scanned in turn until no new objects from 
> it are pulled in.  Then the linker moves on to the next library.  
> Libraries can be grouped so they are repeatedly scanned as a group, 
> rather than individually.  I'll have to check newlib to see whether 
> the dummy lock/unlock functions are in the same object file as 
> something else that is being pulled in.
>
>> Is there a better way of doing this however (a function attribute or 
>> linker option) that tells the compiler or linker that I want to use 
>> my version (implemented in a library or otherwise) of these functions?
>
> hmm, making the dummy malloc_lock malloc_unlock functions in newlib 
> weak would probably be sufficient.  I'll add that to the feature wish 
> list.
>
> nathan
>




More information about the coldfire-gnu-discuss mailing list