Subj : Re: How to deal with errno in a multipthread program To : comp.programming.threads From : David Butenhof Date : Sat Apr 16 2005 03:31 pm icoming wrote: > I thought errno is a global variable, and worried that in a multithread > program the functions which will change the value of errno can not work > well. Historically, yes; errno was a global variable. In fact, POSIX 1003.1, up until the release of the thread amendment 1003.1c-1995, REQUIRED that errno be a global variable despite the fact that ISO C had already fixed that (by requiring that be in scope when using the name 'errno' and that it cannot be legally declared by an application as the traditional 'extern int errno;'). In most any system supporting threads, you'll find that errno is actually a macro dereferencing the pointer return value from a function. (This is carefully designed to allow it to be used on either the left or right side of an assignment.) The pointer returned will differ for each thread. It is a form of thread local data. It might actually use pthread_getspecific() or some non-portable equivalent, or it might refer to a special cell in the thread control block. In theory one could also construct a system where each thread had a privately mapped page so that the address of errno would be the same for all threads but the value would differ (though this is not legal for a POSIX implementation requiring a fully shared address space). By whatever means, though, any implementation of threads (whatever the interface) will have a thread private errno. Even if you encounter one that doesn't, don't waste time trying to work around it... just run away and find a real thread package. ;-) Note, this can be an interesting aspect of real-world programming, when a process mixes code built for threads and code that wasn't. Usually, for binary compatibility with old code, non-threaded compilation does use the old-fashioned 'extern int errno;'. Threaded and non-threaded code running in the same thread may therefore be unable to communicate using 'errno' -- they have different ones. Some have addressed this by making the main thread (that is, the one that started out running main()) use the global "process" errno, while other threads have a private errno. That means any non-threaded code running in the context of the main thread will share 'errno' with threaded code running in the main thread. This is NOT specified by the standard, so it's not a portable assumption. (POSIX doesn't recognize the possibility of "non-threaded" code running on an implementation that supports threads, but most real systems do need to worry about this.) -- Dave Butenhof, David.Butenhof@hp.com HP Utility Pricing software, POSIX thread consultant Manageability Solutions Lab (MSL), Hewlett-Packard Company 110 Spit Brook Road, ZK2/3-Q18, Nashua, NH 03062 .