线程私有数据

一 列举接口

   #include <pthread.h>

   int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *));

   int pthread_key_delete(pthread_key_t key);

   int pthread_setspecific(pthread_key_t key, const void *pointer);

   void * pthread_getspecific(pthread_key_t key);

二 接口来由

1. 多线程中的Errno问题

考虑:线程A 线程B 线程C 软件出错码都通过设置myErrono

在这里插入图片描述
以上模型会带来太多的问题,下图示例其中一种:
线程A本来运行时发生错误,但是因为线程B对Errono清零,线程A返回后无法获取错误码!
在这里插入图片描述

2. 解决方案

在这里插入图片描述

  • 线程A,B,C各自拥有各自的指针数组void* arr[KEY_MAX]
  • 线程A、B、C各自分配一块内存,并把内存指针赋值给arr[Key]
  • 访问Errno实际上变成了如下访问过程:arr[Key] = -1;

可见看到线程A,B,C确实各自分配了各自的内存,但是读者可能会问,这怎么就解决问题了呢?
别急,在这一套数据结构当中,还需要配合一套巧妙的软件过程,参见第三节 实现模拟

三 实现模拟

在这里插入图片描述
有一点需要单独做说明:
因为errno使用动态内存分配技术,在pthread_key_create的时候,传递一个函数指针
buffer_free,这个函数在线程A,B,C 调用pthread_exit或者return时被回调,释放动态内存

#include <iostream>
using namespace std;

extern "C"
{
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
}

extern int myerrno;

#define myerrno *((int*)get_errno())

/*errno_key,理解为一个整型的index*/
static pthread_key_t errno_key;
static pthread_once_t key_once = PTHREAD_ONCE_INIT;

static void buffer_free(void* at_pexit)
{
	cout << "free buffer at " << at_pexit << endl;
	if(at_pexit)
	free(at_pexit);
}

static void make_errno_key(void)
{
	pthread_key_create(&errno_key,buffer_free);
}

void* get_errno()
{
	int* pint = NULL;
	pthread_once(&key_once,make_errno_key);
	if ((pint = (int*)pthread_getspecific(errno_key)) == NULL)
	{
		pint = (int*)malloc(sizeof(int));
		cout << "malloc pint = " << pint << endl;
		pthread_setspecific(errno_key,pint);
	}
	return (void*)pint;
}

void* thread1_func(void* arg)
{
	while(1)
	{
		sleep(1);
		myerrno =1;
		cout << "thread1 &myerrno = " << &myerrno 
			<< " myerrno= " << myerrno << endl;

	}
}
void* thread2_func(void* arg)
{
	while(1)
	{
		sleep(1);
		myerrno =2;
		cout << "thread2 &myerrno = " << &myerrno 
			<< " myerrno= " << myerrno << endl;
	
	}
}

int main(void)
{
	pthread_t thread1;
	pthread_t thread2;
	pthread_create(&thread1,NULL,thread1_func,NULL);
	pthread_create(&thread2,NULL,thread2_func,NULL);
	
	pthread_join(thread1,(void**)NULL);
	pthread_join(thread2,(void**)NULL);
	pthread_key_delete(errno_key);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值