Книга: Programming with POSIX® Threads

9.3.7 Thread-specific data

9.3.7 Thread-specific data

Thread-specific data provides a way to declare variables that have a common "name" in all threads, but a unique value in each thread. You should consider using thread-speciflc data in a threaded program in many cases where a non-threaded program would use "static" data. When the static data maintains context across a series of calls to some function, for example, the context should generally be thread-specific. (If not, the static data must be protected by a mutex.)

pthread_getspecific

void *pthread_getspecific (

pthread_key_t key);

Return the current value of key in the calling thread. If no value has been set for key in the thread, NULL is returned.

References: 5.4, 7.2, 7.3.1 Headers: <pthread.h>

Errors: The effect of calling pthread_getspecific with an invalid key is un-

defined. No errors are detected.

Hint: Calling pthread_getspecific in a destructor function will return

NULL. Use destructor's argument instead.

pthread_key_create

int pthread_key_create (

pthread_key_t *key,

void (*destructor)(void *));

Create a thread-specific data key visible to all threads. All existing and new threads have value NULL for key until set using pthread_setspecific. When any thread with a non-NULL value for key terminates, destructor is called with key's current value for that thread.

References: 5.4,7.2,7.3.1 Headers: <pthread.h>

Errors: [EAGAIN] insufficientresourcesorPTHREAD_KEYS_MAxexceeded.

[ENOMEM] insufficient memory to create the key. Hint: Each key (pthread_key_t variable) must be created only once; use

a mutex or pthread_once.

pthread_key_delete

int pthread_key_delete (

pthread_key_t key);

Delete a thread-specific data key. This does not change the value of the thread-specific data key for any thread and does not run the key's destructor in any thread, so it should be used with great caution.

References: 5.4

Headers: <pthread.h>

Errors: [EINVAL]keyisinvalid.

Hint: Use only when you know all threads have NULL value.

pthread_setspecific

int pthread_setspecific (

pthread_key_t key, const void *value);

Associate a thread-specific value within the calling thread for the specified key.

References: 5.4, 7.2, 7.3.1

Headers: <pthread.h>

Errors: [ENOMEM]insufficient memory.

[EINVAL] key is invalid. Hint: If you set a value of NULL, the key's destructor will not be called at

thread termination.

Оглавление книги


Генерация: 0.049. Запросов К БД/Cache: 0 / 2
поделиться
Вверх Вниз