[Proj] libproj4 thread safety

Glynn Clements glynn at gclements.plus.com
Mon Feb 28 05:07:47 EST 2005

Gerald Evenden wrote:

> > This is the first solution : replace the pj_errno access with 2 
> > accessor functions you declare but the client defines. Then you use 
> > these functions to set or get pj_errno inside the library. Client code 
> > must implement both function with thread local storage or anything 
> > else.
> Ok, I think I understand. But how can the library exist in the
> unsophisticated non-thread world without bothering users with this
> "odd" requirement. I do not understand how the naming of these
> functions is handled with multiple copies.(?)

The way in which the GNU C library implements errno is to use a
preprocessor macro to give each thread its own copy:

	/* Function to get address of global `errno' variable.  */
	extern int *__errno_location (void) __THROW __attribute__ ((__const__));

	/* When using threads, errno is a per-thread value.  */
	#   define errno (*__errno_location ())

The __errno_location() function returns a pointer to thread-specific
memory (via pthread_getspecific()).

The reason for the indirection is that errno must behave as a
variable, in the sense that assignments must be supported, e.g.:

	errno = 0;
	if (errno != 0)
> How are error flags handled for the math library in the threaded
> environment? Close to the same issue. I do not do much checking here
> as the code does so much manipulation to avoid math library
> problems.

The defined interface (in <fenv.h>) uses functions to test and modify
the flags. The flags themselves are stored in the FPU's status
registers, which are automatically saved and restored across a context
switch, so each thread has its own set of flags.

Glynn Clements <glynn at gclements.plus.com>

More information about the Proj mailing list