线程的私有数据

线程的私有数据

概述

我们知道,线程之间的数据是共享的;这时候我们就在思考,线程有时也需要有自己独有的数据,而无需与其他线程共享。于是就提出了线程的私有数据;具体实现原理而后研究补充。

相关函数

int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
    key:线程私有数据创建一个新键,并通过key指向新创建的键缓冲区
    destructor:对应的析构函数,线程结束时自动调用

int pthread_setspecific(pthread_key_t key, const void *value);
    key:线程私有数据键
    value:线程私有数据值

void *pthread_getspecific(pthread_key_t key);
    return:根据key,获取私有数据的值

示例代码

 #include <string.h>
 #include <pthread.h>
 #include <stdio.h>
 #include <stdlib.h>

 pthread_key_t key;

 // 可能被线程A调用
 // 也可能线程B调用
 void foo()
 {
     char* p = (char*)pthread_getspecific(key);
     printf("%s\n", p);
 }

 void my_malloc()
 {
     // 去这个线程的内存池去申请内存
     void* mempool = pthread_getspecific(key);
   //  __my_malloc(mempool, ...);
 }

 void* thread_func(void* ptr)
 {
     // setspecific,需要在线程中调用,当然也可以在主线程中调用
     // 为这个线程设置私有数据
     pthread_setspecific(key, ptr);

     foo();
     my_malloc();
     return NULL;
 }

 void free_func(void* ptr)
 {
     printf("free call\n");
     free(ptr);
 }

 int main()
 {
     //int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
     //key:线程私有数据键,destructor:对应的析构函数
     pthread_key_create(&key, free_func);

     pthread_t tid1, tid2;
     pthread_create(&tid1, NULL, thread_func, strdup("thread1"));
     pthread_create(&tid2, NULL, thread_func, strdup("thread2"));

     pthread_join(tid1, NULL);
     pthread_join(tid2, NULL);

 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值