打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
多线程之私有数据(YC)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>

pthread_key_t key;

void *thread1(void *arg)
{
    int i=10;
    int tid=pthread_self();
    printf("In thread 1,ID :%u\n",tid);
    printf("Set the private value1\n");
    pthread_setspecific(key,&i);
    sleep(2);  //等待线程2改变数据,看是否有影响
    printf("The value in thread1 is %d\n",(*(int *)pthread_getspecific(key)));
}

void *thread2(void *arg)
{
    int j=20;
    int tid=pthread_self();
    printf("In thread 2,ID :%u\n",tid);
    printf("Set the private value2\n");
    pthread_setspecific(key,&j);
    sleep(1);
    printf("The value in thread2 is %d\n",(*(int *)pthread_getspecific(key)));
}

int main(void)
{
    pthread_t td1,td2;
    pthread_key_create(&key,NULL);
    pthread_create(&td1,NULL,(void *)thread1,NULL);
    pthread_create(&td2,NULL,(void *)thread2,NULL);
    pthread_join(td1,NULL);  //等待子线程结束
    pthread_join(td2,NULL);  //等待子线程结束
    pthread_key_delete(key);
    return 0;
}

运行结果:



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
线程私有数据(TSD)
pthread编程基础
linux 多线程编程 Thread Specific Data (TSD)
Linux线程之线程线程组进程轻量级进程(LWP)
Posix线程编程指南(2)
Linux多线程编程(不限Linux)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服