Thread Safety - NAG C Library

The NAG C Library is thread safe by design; all communication between routines is via argument lists, and, with the exception of one chapter (g05, Random Number Generators), no use of read and write static storage is made.
In Chapter g05, for efficiency, global variables have been used internally for communication. Simultaneous access to these global variables by multiple threads has been guarded against using thread mutexes. For UNIX machines, these mutexes come from the POSIX standard thread library (ANSI/IEEE POSIX 1003.1c-1995), also known as pthreads. For PC implementations of the NAG C Library, the mutexes are those implemented by the Microsoft thread package.

The NAG C Library is therefore thread safe with respect to the thread package against which it was built, either pthreads or Microsoft threads. Some older UNIX architectures did not have implementations of pthreads available, and implementations of the NAG C Library on such architectures could not therefore be made thread safe - though of course on such machines it would not be possible to write a POSIX multi-threaded program anyway.

Although the NAG C Library is thread safe, sometimes care must be taken to use it in a thread-safe way. In particular, this is the case with two chapters, Chapter c05 (Roots of One or More Transcendental Equations), and Chapter d01 (Quadrature). In these chapters, the solution of a problem usually involves a user-supplied routine being passed to the NAG Library routine, the user-supplied C routine being called to evaluate the mathematical function which is the object of the problem. It is sometimes the case that the user would like the evaluation function to communicate with the main program, to pass relevant information involved in the function evaluation. The simplest way to do this is to use global variables for communication, but these global variables render the resulting code unsuitable for use by multiple threads simultaneously.

Using pthread or Microsoft thread package functionality, it is perfectly possible for the user to avoid this problem by writing code which passes thread-specific data between main program and evaluation function. As an alternative to this method, however, where relevant we have provided alternative versions of the NAG Library routines. These alternative routines have an extra argument which can be used for safe communication of additional data if it is required. Please see documentation for nag_1d_quad_gen (d01ajc) and nag_1d_quad_gen_1 (d01sjc) for examples.

Finally we recommend that when using the C Library error mechanism, the output is switched off (by setting fail.print = FALSE). See the Essential Introduction to the NAG C Library.