stdio thread safety

Corinna Vinschen
Tue Jun 4 08:21:00 GMT 2013

On Jun  3 11:04, Carl Norum wrote:
> Hi newlib list,
> I'm working on an embedded ARM project, and I'm trying to figure out
> my C library options situation.  I've used newlib before, but this is
> the first time I'll have tried to use it in a multithreaded
> environment.  sys/lock.h appears to just make all of the locking
> primitives no-ops, though.  Is the thread-safety part of newlib still
> a work in progress?  Or am I missing something with how to hook in?
> It looks like the fprintf implementation has the calls to lock/unlock
> files in the right places, but those calls just don't do anything.
> The __malloc_lock and __malloc_unlock, in contrast, do appear to work
> and do the right thing - I implement those functions and they get
> called.  However, if I implement "__lock_init_recursive", for example,
> newlib doesn't end up making any calls to it.  I'm guessing that's a
> result of the library being built with that lock.h header mentioned
> above.

Just override the definitions in sys/lock.h by providing your own
sys/lock.h, along the lines of:

  typedef __your_lock_type _LOCK_T;
  typedef __your_lock_recursive_type _LOCK_T;

  #define __lock_init(__lock)  __your_lock_init(__lock)
  #define __lock_init_recursive(__lock) __your_lock_init_recursive(&__lock)
  #define __lock_close(__lock) __your_lock_fini(&__lock)

> Right now, I've worked around it by using the linker to make wrap
> functions that lock access to stdio, but that's not very pretty.  I
> may have to do something like this anyway, though - the new
> nano-malloc looks good, but it's explicitly not thread safe (the
> MALLOC_LOCK and MALLOC_UNLOCK functions are defined to be nothing in
> the source).

Yes, that has been discussed and the original developer is hopefully
looking into adding thread safety soon.


Corinna Vinschen
Cygwin Maintainer
Red Hat

More information about the Newlib mailing list