线程特有数据==线程内静态变量

44 篇文章 0 订阅
19 篇文章 0 订阅

函数应用背景:在单线程程序中,函数经常使用全局变量或静态变量,这是不会影响程序的正确性的,但如果线程调用的函数使用全局变量或静态变量,则很可能引起编程错误,因为这些函数使用的全局变量和静态变量无法为不同的线程保存各自的值,而当同一进程内的不同线程几乎同时调用这样的函数时就可能会有问题发生。而解决这一问题的一种方式就是使用线程特定数据的机制。

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

#define NUM 2

int g_key_size = 10;
static pthread_key_t msg_key;

static void msg_key_destructor(void* p)
{
        free(p);
}

void* get_msg_key()
{
        int status;
        void* key;
        if ((key = pthread_getspecific(msg_key)) == NULL) {
                key = malloc(g_key_size);
                if (key == NULL){
                        printf("10, %d\n", errno);
                        abort();
                }
                status = pthread_setspecific(msg_key, key);
                if (status != 0){
                        printf("20 %d\n", status);
                        abort();
                }
        }
        return key;

}

void *write_main(void *arg)
{
        int     *key = NULL;

        while(1){
                key = get_msg_key();
                *key = pthread_self();
                printf("%d:%d\n", pthread_self(), *key);
                if(pthread_self() != *key)
                        printf("no\n");
        }
}

main()
{
        int             stat;
        pthread_t       pth[NUM];
        int             i;

        printf("start\n");
        stat = pthread_key_create(&msg_key, msg_key_destructor);
        if (stat != 0) {
                return stat;
        }

        for(i=0; i<NUM; i++){
                stat = pthread_create(&pth[i], NULL, write_main, NULL);
                if(stat != 0)
                        return errno;
        }

for(i=0; i<NUM; i++)
                pthread_join(pth[i], NULL);

        printf("over\n");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值