进程里的多个线程,共享该进程的全局变量。Posix定义了一种Thread-Specific Data,它看起来是个全局变量,所有线程都可以使用它,而它的值在每一个线程中又是单独存储的。
代码语言:javascript复制#ifdef _WRS_KERNEL
#define _POSIX_THREAD_KEYS_MAX 256
#else
#define _POSIX_THREAD_KEYS_MAX 128
#endif
/*
* 创建一个Thread-Specific Data, 存于<pKey>, 其值为NULL.
* 如果数量超过_POSIX_THREAD_KEYS_MAX, 则返回EAGAIN(11).
*
* 线程终止时, 非NULL的<destructor>将被调用, 入参为Thread-Specific Data
*
* 当所有线程都不使用这个key时, User应该调用pthread_key_delete()
*/
int pthread_key_create
(
pthread_key_t *pKey,
void (*destructor)(void *)
);
/*
* 删除Thread-Specific Data <key>,
* 这里不会调用<destructor>.
*/
int pthread_key_delete
(
pthread_key_t key
);
/*
* 设置当前线程的Thread-Specific Data <key>的值为<value>.
* 如果<value>为NULL,则后续的<destructor>不被调用.
*/
int pthread_setspecific
(
pthread_key_t key,
void *value
);
/*
* 返回当前线程的Thread-Specific Data <key>的值.
*/
void *pthread_getspecific
(
pthread_key_t key
);
写个例子
代码语言:javascript复制
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static pthread_key_t bufKey;
void *subThread(void *args)
{
char *buf = calloc(30, 1);
pthread_setspecific(bufKey, buf);
sprintf(buf, "thread %#x stopsn", (UINT32)pthread_self());
return NULL;
}
void threadStop(void *buf)
{
printf(buf);
free(buf);
}
#ifdef _WRS_KERNEL
int testThread()
#else
int main()
#endif
{
pthread_t tid1;
pthread_t tid2;
pthread_key_create(&bufKey, threadStop);
pthread_create(&tid1, NULL, subThread, NULL);
pthread_create(&tid2, NULL, subThread, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_key_delete(bufKey);
return 0;
}