This is the mail archive of the glibc-linux@ricardo.ecn.wfu.edu mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Is the standard IO library thread safe?


On Thu, 16 Sep 1999, Andy Tai wrote:

> Date: Thu, 16 Sep 1999 11:22:13 -0700 (PDT)
> From: Andy Tai <atai@sdcc3.ucsd.edu>
> Reply-To: glibc-linux@ricardo.ecn.wfu.edu
> To: glibc-linux@ricardo.ecn.wfu.edu
> Subject: Is the standard IO library thread safe?
> 
> 
> Hi, I wonder is the standard I/O library thread safe?  For

No, standard I/O streams are not thread safe in the POSIX model. They
expose locks that the programmer must manage explicitly.

> example, I was using fprintf(stderr, ...)  in multithreaded programs, and it
> causes random crashes.  After I add locks around these fprintf calls,
> eeverything is fine.

You should consider using the locks that are built into streams:  
flockfile() and friends. There are also locked and unlocked versions of
many of the I/O functions, so that you can lock a stream, and execute a
group of operations atomically. For example, you could do:

	flockfile(file);
	putc_locked('a', file);
	pubc_locked('b', file);
	putc_locked('c', file); /* error checking omitted */
	funlockfile(file);

If all other uses of file use correct locking, the above should
write "abc" to the stream. 


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]