Thread-specific data

Typical applications that are not threaded use global storage.

When changing the application or application services to run in a multithreaded application, you must use a synchronization technique to protect global storage from being changed by multiple threads at the same time. Thread-specific data allows a thread to maintain its own global storage that is hidden from the other threads.

Due to the design of the application, threads might not function correctly if they share the global storage of the application. If eliminating the global storage is not feasible, you should consider using thread-specific data.

Consider the example of a server that stores information about the client and the current transaction in global storage. This server is never able to share the client information in a multithreaded environment without significant redesign. The application can instead pass the client information from function to function instead of using the global client information.

However, the application can maintain the client and transaction information in thread-specific data more easily than it can be modified to eliminate the use of global storage. When each new thread is created, the thread uses a global identifier (or key) to create and store its thread-specific data. Each client (thread) then has unique but global client data.

In addition, some API sets provide a way for the system to automatically call a data destructor function that cleans up the thread-specific data when a thread ends.

Related concepts
One-time initialization and thread safety