线程私有存储空间的全局变量pthread_key_t

线程私有存储空间的全局变量pthread_key_t

一、api的使用

1.pthread_key_t key;定义一个该类型的变量,作为key,用来对应线程的私有存储空间的value
在这里插入图片描述
2.pthread_key_create(&key, NULL);创建(初始化)变量key,使它能够区别不同线程中,这个key所对应的value
在这里插入图片描述
3.pthread_setspecific(key, &i);在线程中,通过全局变量key,将值传入线程的私有空间中
在这里插入图片描述

4.int *p = (int *)pthread_getspecific(key);在线程中,通过全局变量key,将线程的私有空间中的值取出来。
在这里插入图片描述

看似是全局变量,然而全局的只是key值,对于不同的线程对应的value值是不同的(通过pthread_setspcific()和pthread_getspecific()设置),key对每个线程中的value都能进行绑定与识别。
一个全局变量key,每个线程对应 特定的指针void*。

由于pthread_setspecific第二个参数是void*, 因此可以传入任意类型的值,如int,字符,结构体等。

总之,全局变量key,在不同线程中对应的value是不一样的。

二、案例

#include<pthread.h>
#include<stdio.h>
#define THREAD_COUNT 3

pthread_key_t key;
typedef void *(*thread_cb)(void *);


void print_thread1_key(void) {

	int *p = (int *)pthread_getspecific(key);//将值从私有空间中取出来

	printf("thread 1 : %d\n", *p);

}

//线程1 的回调函数
void *thread1_proc(void *arg) {

	int i = 5;	
	pthread_setspecific(key, &i);//将 i传入私有空间中

	print_thread1_key();

}

void print_thread2_key(void) {

	char *ptr = (char *)pthread_getspecific(key);

	printf("thread 2 : %s\n", ptr);

}

//线程2 的回调函数
void *thread2_proc(void *arg) {

	char *ptr = "thread2_proc";
	pthread_setspecific(key, ptr);
	print_thread2_key();
	
}


struct pair {
	int x;
	int y;
};


void print_thread3_key(void) {

	struct pair *p = (struct pair *)pthread_getspecific(key);

	printf("thread 3  x: %d, y: %d\n", p->x, p->y);

}

//线程3 的回调函数
void *thread3_proc(void *arg) {

	struct pair p = {1, 2};

	pthread_setspecific(key, &p);
	print_thread3_key();
}

int main(){
    
    pthread_t thid[THREAD_COUNT] = {0};//3个线程id
    pthread_key_create(&key, NULL);//创建key,这个全局变量可以认为是线程内部的私有空间

    thread_cb callback[THREAD_COUNT] = {//线程的回调函数
		thread1_proc,
		thread2_proc,
		thread3_proc
	};

	int i = 0;int count = 0;
	for (i = 0;i < THREAD_COUNT;i ++) {//创建线程
		pthread_create(&thid[i], NULL, callback[i], &count);
	}

	for (i = 0;i < THREAD_COUNT;i ++) {
		pthread_join(thid[i], NULL);//主线程需要等待子线程执行完成之后再结束
	}

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菊头蝙蝠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值