Returning thread-safe values from an UDF

By: Borland Staff

Abstract: There are three ways to manage thread-local storage when returning values from a UDF.

Problem:
What is the best way to return thread-safe values from an UDF?

Solution:

There are three ways to manage thread-local storage when returning values from a UDF:

1)FREE_IT: Use this argument to the DECLARE EXTERNAL FUNCTION statement to free that
memory allocated by a malloc() call within the UDF.  Declaring the output parameters this way tells
the server that the return value is a pointer to a malloc'ed buffer and that the server should free the
memory. The value being passed back is thread-safe using this convention.

Note: the FREE_IT keyword is a 5.x feature only.  It will NOT work with 4.x kits

2)Thread-local storage: Declare thread-local variables (threadvars in Delphi) to maintain the value
 in and out of the UDF call.  Since a thread may be recycled, thread-local variables should not save
state information.  The values being passed back are thread-safe using this convention.

3)RETURNS PARAMETER N: Use this argument to the DECLARE EXTERNAL FUNCTION statement
that specifies that the return value for the UDF is stored in the input parameter N.  This feature has
been deprecated and was not certified under 5.x; it was by accident that it was documented in the
manuals.  With that said, use at your own risk.  The only additional concern is that the output value's
length can not exceed that of the input variable's declaration. Under the pre-5.x engine, the values
being passed back were thread-safe.

It is important to note that there is a difference between:

A)Declaring a global variable and synchronizing it between threads.

AND

B)Declaring a thread-local variable through the compiler's thread-local storage model.

The InterBase engine will manage UDF thread-safe variables in case (B), where sufficient locking
routines are put into place to guarantee the value.  Also note that InterBase will copy the return value
to a new memory location soon after the function is completed; this ensures the integrity of the
thread-local storage value. For more information on thread-safe local storage, please refer to that
section in the WIN32.HLP file or "Advanced Windows" by Jeffrey Richter.  

Server Response from: ETNASC03