Writing reentrant and thread-safe code

Source: Internet
Author: User
Tags strtok
ArticleDirectory
    • Related information

In single-threaded processes there is only one flow of control. the Code executed by these processes thus need not to be reentrant or thread-safe. in multi-threaded programs, the same functions and the same resources may be accessed concurrently by several flows of control. to protect resource integrity, code written for multi-threaded programs must be reentrant and thread-safe.

This section provides information for writing reentrant and thread-safe programs. it does not cover the topic of writing thread-efficient programs. thread-efficient programs are efficiently parallpoliced programs. this can only be done during the design of the program. existing single-threaded programs can be made thread-efficient, but this requires that they be completely redesigned and rewritten.

 

    • Understanding reentrance and thread-Safety
    • Making a function Reentrant
    • Making a function thread-safe
    • Reentrant and thread-safe Libraries
Understanding reentrance and thread-Safety

Reentrance and thread-safety are both related to the way functions handle resources. reentrance and thread-safety are separate concepts: a function can be either reentrant, thread-safe, both, or neither.

Reentrance

A reentrant function does not hold static data over successive CILS, nor does it return a pointer to static data. all data is provided by the caller of the function. A reentrant function must not call non-reentrant functions.

A non-reentrant function can often, but not always, be identified by its external interface and its usage. For example, StrtokSubroutine is not reentrant, because it holds the string to be broken into tokens. CtimeSubroutine is also not reentrant; it returns a pointer to static data that is overwritten by each call.

Thread-Safety

A thread-safe function protects shared resources from concurrent access by locks. Thread-safety concerns only the implementation of a function and does not affect its external interface.

In C, local variables are dynamically allocated on the stack. therefore, any function that does not use static data or other shared resources is trivially thread-safe. for example, the following function is thread-safe:

/* Thread-safe function */INT diff (int x, int y) {int delta; Delta = Y-X; If (delta <0) Delta =-delta; return delta ;}

The use of global data is thread-unsafe. it shoshould be maintained per thread or encapsulated, so that its access can be serialized. A thread may read an error code corresponding to an error caused by another thread. in Aix, each thread has its ownErrnoValue.

Making a function Reentrant

In most cases, non-reentrant functions must be replaced by functions with a modified interface to be reentrant. non-reentrant functions cannot be used by multiple threads. furthermore, it may be impossible to make a non-reentrant function thread-safe.

Returning data

Except non-reentrant functions return a pointer to static data. This can be avoided in two ways:

    • Returning dynamically allocated data. in this case, it will be the caller's responsibility to free the storage. the benefit is that the interface does not need to be modified. however, backward compatibility is not ensured; existing single-threaded programs using the modified functions without changes wocould not free the storage, leading to memory leaks.
    • Using caller-provided storage. This method is recommended, although the interface needs to be modified.

For example,StrtoupperFunction, converting a string to uppercase, cocould be implemented as in the following code fragment:

 
/* Non-reentrant function */char * strtoupper (char * string) {static char buffer [max_string_size]; int index; For (Index = 0; string [Index]; index ++) buffer [Index] = toupper (string [Index]); buffer [Index] = 0 return buffer ;}

This function is not reentrant (nor thread-safe). Using the first method to make the function reentrant, the function wocould be similar to the following code fragment:

 
/* Reentrant function (a poor solution) */char * strtoupper (char * string) {char * buffer; int index;/* error-checking shocould be completed MED! */Buffer = malloc (max_string_size); For (Index = 0; string [Index]; index ++) buffer [Index] = toupper (string [Index]); buffer [Index] = 0 return buffer ;}

A better solution consists of modifying the interface. The caller must provide the storage for both input and output strings, as in the following code fragment:

 
/* Reentrant function (a better solution) */char * strtoupper_r (char * in_str, char * out_str) {int index; For (Index = 0; in_str [Index]; index ++) out_str [Index] = toupper (in_str [Index]); out_str [Index] = 0 return out_str ;}

The non-reentrant Standard C library subroutines were made reentrant using the second method. This is discussed below.

Keeping data over successive CILS

No data shoshould be kept over successive CILS, because different threads may successively call the function. if a function needs to maintain some data over successive CILS, such as a working buffer or a pointer, this data shoshould be provided by the caller.

Consider the following example. A function returns the successive lowercase characters of a string. the string is provided only on the first call, as withStrtokSubroutine. The function returns 0 when it reaches the end of the string. The function cocould be implemented as in the following code fragment:

/* Non-reentrant function */Char lowercase_c (char * string) {static char * buffer; static int index; char C = 0; /* stores the string on first call */If (string! = NULL) {buffer = string; Index = 0;}/* searches a lowercase character */For (; C = buffer [Index]; index ++) {If (islower (c) {index ++; break ;}} return C ;}

This function is not reentrant. To make it reentrant, the static data,IndexVariable, needs to be maintained by the caller. The reentrant version of the function cocould be implemented as in the following code fragment:

 
/* Reentrant function */Char reentrant_lowercase_c (char * string, int * p_index) {char C = 0; /* No initialization-the caller shoshould have done it * // * searches a lowercase character */For (; C = string [* p_index]; (* p_index) ++) {If (islower (c) {(* p_index) ++; break ;}} return C ;}

The interface of the function changed and so did its usage. The caller must provide the string on each call and must initialize the index to 0 before the first call, as in the following code fragment:

 
Char * my_string; char my_char; int my_index;... my_index = 0; while (my_char = reentrant_lowercase_c (my_string, & my_index )){...}
Making a function thread-safe

In multi-threaded programs, all functions called by multiple threads Must Be thread-safe. however, there is a workaround for using thread unsafe subroutines in multi-threaded programs. note also that non-reentrant functions usually are thread-unsafe, but making them reentrant often makes them thread-safe, too.

Locking shared resources

Functions that use static data or any other shared resources, such as files or terminals, must serialize the access to these resources by locks in order to be thread-safe. for example, the following function is thread-unsafe:

 
/* Thread-unsafe function */INT increment_counter () {static int counter = 0; counter ++; return counter ;}

To be thread-safe, the static variableCounterNeeds to be protected by a static lock, as in the following (pseudo-code) Example:

 
/* Pseudo-code thread-safe function */INT increment_counter (); {static int counter = 0; static lock_type counter_lock = lock_initializer; lock (counter_lock); counter ++; unlock (counter_lock); return counter ;}

In a multi-threaded application program using the threads library, mutexes shoshould be used for serializing shared resources. independent libraries may need to work outside the context of threads and, thus, use other kinds of locks.

A workaround for thread-unsafe Functions

It is possible to use thread-unsafe functions called by multiple threads using a workaround. this may be useful, especially when using a thread-unsafe library in a multi-threaded program, for testing or while waiting for a thread-safe version of the library to be available. the workaround leads to some overhead, because it consists of serializing the entire function or even a group of functions.

  • use a global lock for the library, and lock it each time you use the library (calling a library routine or using a library global variable ), as in the following pseudo-code fragments:

    /* This is pseudo-code! */Lock (library_lock); library_call (); unlock (library_lock); lock (library_lock); X = library_var; unlock (library_lock ); 

    this solution can create performance bottlenecks because only one thread can access any part of the library at any given time. the solution is acceptable only if the library is seldom accessed, or as an initial, quickly implemented workaround.

  • Use a lock for each library component (routine or global variable) or group of components, as in the following pseudo-code fragments:
    /* This is pseudo-code! */Lock (library_modulea_lock); library_modulea_call (); unlock (library_modulea_lock); lock (library_moduleb_lock); X = library_moduleb_var; unlock (library_moduleb_lock );

    This solution is somewhat more complicated to implement than the first one, but it can improve performance.

Because this workaround shocould only be used in application programs and not in libraries, mutexes can be used for locking the library.

Reentrant and thread-safe Libraries

Reentrant and thread-safe libraries are useful in a wide range of parallel (and asynchronous) programming environments, not just within threads. thus it is a good programming practice to always use and write reentrant and thread-safe functions.

Using Libraries

Several Libraries shipped with the AIX base operating system are thread-safe. In the current version of Aix, the following libraries are thread-safe:

    • Standard C library (Libc.)
    • Berkeley compatibility Library (Libbsd.).

Some of the Standard C subroutines are non-reentrant, such asCtimeAndStrtokSubroutines. The reentrant version of the subroutines have the name of the original subroutine with a suffix_ R(Underscore R ).

When writing multi-threaded programs, the reentrant versions of subroutines shocould be used instead of the original version. For example, the following code fragment:

 
Token [0] = strtok (string, separators); I = 0; do {I ++; token [I] = strtok (null, separators );} while (token [I]! = NULL );

Shocould be replaced in a multi-threaded program by the following code fragment:

 
Char * pointer ;... token [0] = strtok_r (string, separators, & pointer); I = 0; do {I ++; token [I] = strtok_r (null, separators, & pointer);} while (token [I]! = NULL );

Thread-unsafe libraries may be used by only one thread in a program. the uniqueness of the thread using the library must be ensured by the programmer; otherwise, the program will have unexpected behavior, or may even crash.

Converting Libraries

This information highlights the main steps in converting an existing library to A reentrant and thread-safe Library. It applies only to C language libraries.

    • identifying exported global variables. those variables are usually defined in a header file with the export keyword.

      exported global variables shocould be encapsulated. the variable shoshould be made private (defined with the static keyword in the Library source code ). access (read and write) subroutines shoshould be created.

    • identifying static variables and other shared resources. static variables are usually defined with the static keyword.

      locks shoshould be associated with any shared resource. the granularity of the locking, thus choosing the number of locks, impacts the performance of the library. to initialize the locks, the one-time initialization facility may be used.

    • identifying non-reentrant functions and making them reentrant. See making a function reentrant.
    • identifying thread-unsafe functions and making them thread-safe. See making a function thread-safe.
Related information

Parallel Programming Overview

Thread Programming Concepts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.