Linux多线程pthread_key_create

本文通过示例代码展示了在Linux环境下如何使用pthread_key_t进行线程特定数据的创建与管理,包括pthread_key_create和pthread_setspecific等函数的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Linux 多线程应用编程 pthread_key_create

示例代码:


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


pthread_key_t key;
struct for_test {
    int i;
    float k;
};


void *thread1 (void *arg)
{
    struct for_test data;
    data.i = 1;
    data.k = 1.23;
    pthread_setspecific (key, &data);
    printf ("struct_data的地址为 0x%p\n", &(data));
    printf ("thread1 pthread_getspecific(key)返回的地址为:0x%p\n", (struct for_test *)pthread_getspecific(key));
    printf ("thread1 第一次利用 pthread_getspecific(key)打印线程中与key关联的结构体中成员值:\ndata.i:%d\ndata.k: %f\n", ((struct for_test*)pthread_getspecific (key))->i, ((struct for_test *)pthread_getspecific(key))->k);


    sleep(2);
    printf ("\n\nthread1 第二次利用 pthread_getspecific(key)打印线程中与key关联的结构体中成员值:\ndata.i:%d\ndata.k: %f\n", ((struct for_test*)pthread_getspecific (key))->i, ((struct for_test *)pthread_getspecific(key))->k);

}


void *thread2 (void *arg)
{
    int num = 10;
    sleep (1);
    printf ("\n\nthread2 变量 num 的地址为 0x%p\n",  &num);
    pthread_setspecific (key, &num);
    printf ("thread2 pthread_getspecific(key)返回的地址为:0x%p\n", (int *)pthread_getspecific(key));
    printf ("thread2 利用 pthread_getspecific(key)打印线程中与key关联的整型变量temp 值:%d, k = %f\n", *((int *)pthread_getspecific(key)), ((struct for_test *)pthread_getspecific(key))->k);
}


int main (void)
{
    pthread_t tid1, tid2;
    pthread_key_create (&key, NULL);
    pthread_create (&tid1, NULL, (void *)thread1, NULL);
    pthread_create (&tid2, NULL, (void *)thread2, NULL);
    pthread_join (tid1, NULL);
    pthread_join (tid2, NULL);
    pthread_key_delete (key);


    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值