Thread-Specific Storage

来源:互联网 发布:黑客 知乎 编辑:程序博客网 时间:2024/05/16 18:54

This article told the last pattern illustrated in POSA2 - Thread Specific Storage, which is such a common mechanism provided by some  operating systems or the third libraries.

The Thread-Specific Storage design pattern allows multiple threads to use one 'logically global' access point to retrieve an object that is local to a thread, without incurring locking overhead on each object access.

The Thread-Specific Storage pattern is composed of six participants:

Thread-Specific object: A thread-specific object is an instance of an object that can be accessed only by a particular thread.

Key: A thread identifies a thread-specific object using a key that is allocated by a key factory.

Key factory: Keys generated by the key factory are assigned from a single range of values to ensure that each thread-specific object is 'logically' global.

Thread-Specific object set: A thread-specific object set contains the collection of thread-specific objects that are associated with a particular thread. Each thread has its own thread-specific object set. Internally, this thread-specific object set defines a pair of methods, which we call set() and get(), to map the globally-managed  set of keys to the thread-specific objects stored in the set. Clients of a thread-specific object set can obtain a pointer to a particular thread-specific object by passing a key that identifies the object as a parameter to get(). The client can inspect or modify the object via the pointer returned by the get() method. Similarly, clients can add a pointer to a thread-specific object into the object set by passing the pointer to the object and its associated key as parameters to set().

Thread-Specific object proxy: A thread-specific object proxy can be defined to enable clients to access a specific type of thread-specific object as if it were on ordinary object. If proxies are not used, clients must access thread-specific object sets directly and use keys explicitly, which is tedious and error-prone. Each proxy instance stores a key that identifies the thread-specific object uniquely. Thus, there is one thread-specific object per key, per thread.

Application threads: Application threads are clients that use threaad-specific object proxies to access particular thread-specific objects that reside in thread-specific storage. To an application thread, the method appears to be invoked on an ordinary obejct, when in fact it is invoked on a thread-specific object. Multiple application threads can use the same thread-specific object proxy to access their unique thread-specific objects. A proxy uses the identifier of the application thread that calls its interface methods to differentiate between the thread-specific objects it encapsulates.

 

原创粉丝点击