TutTsdKeyCreate create a thread-specific data key
T_BOOL TutTsdKeyCreate(key_return
,destructor_func
) T_TSD_KEY *key_return
; T_TSD_KEY_DESTRUCTOR_FUNCdestructor_func
;
key_return
location of a T_TSD_KEY variable to initialize
destructor_func
cleanup function to call at thread exit (may be NULL
)
TRUE
if a new TSD key was successfully created, FALSE
otherwise.
If TutTsdKeyCreate fails, it returns FALSE
and sets the global SmartSockets error number to one of:
TutTsdKeyCreate creates a new thread-specific data key and initializes key_return
with its value. Thread-specific data keys provide a thread-safe substitute for global and file-scope variables. Rather than directly storing a value that is shared by several functions in a global variable, a TSD key can be created. The value may then be placed in memory allocated from the heap and referenced by a unique T_PTR value for each thread. Each function that references the value must then use the TSD key to locate the shared value on the heap with the T_PTR value for the currently executing thread.
The destructor_func
allows the strategy outlined above to be used without fear of introducing memory leaks as threads are created and exited. Whenever a utility library thread exits, it iterates through all of its TSD values and calls any cleanup functions specified when the keys for those values were created.
Not all platforms that support threads have native support for TSD. An even smaller subset supports TSD cleanup functions. The utility library implements these features across all platforms (using native support where it is available and internal support code where it is not), but necessarily only for utility library threads. Thus, code that calls utility library TSD functions from native threads may leak memory when the native thread exits and the TSD cleanup functions are not called.
TutTsdGetValue, TutTsdKeyDestroy, TutTsdSetValue
This example uses TSD to provide a TutOut-like function that uses a different output file handle for each thread:
T_TSD_KEY my_output_key; T_INT4 my_printf(T_STR fmt, ...) { FILE *my_output; va_list var_arg_list; T_INT4 result; if (!TutTsdGetValue(my_output_key, &my_output)) {/* default to duplicate stdout */
my_output = fdopen(dup(fileno(stdout)), "a"); if (!TutTsdSetValue(my_output_key, my_output)) {/* error */
} } va_start(var_arg_list, fmt); result = vfprintf(my_output, fmt, var_arg_list); va_end(var_arg_list); return result; } . . . void my_output_cleanup(T_PTR my_output) { if (my_output != NULL) { fclose((FILE *)my_output); } } int main() { if (!TutTsdKeyCreate(&my_output_key, my_output_cleanup)) {/* error */
} . . . if (!TutTsdKeyDestroy(my_output_key)) {/* error */
} return T_EXIT_SUCCESS; }
TIBCO SmartSockets™ Utilities Software Release 6.8, July 2006 Copyright © TIBCO Software Inc. All rights reserved www.tibco.com |