• 线程共享全局变量和私有全局变量


    共享全局变量实例:

    #include <stdio.h>
    #include <pthread.h>
    #include <unistd.h>
    #include <stdlib.h>
    int key=100;
    void *helloworld_one(char *argc)
    {
        printf("the message is %s
    ",argc);
        key=10;
        printf("key=%d, the child is %u
    ",key,pthread_self());
        return 0;
    }
    
    void *helloworld_two(char *argc)
    {
        printf("the message is %s
    ",argc);
        sleep(1);
        printf("key=%d, the child is %u
    ",key,pthread_self());
    }
    
    int main()
    {
        pthread_t thread_id_one;
        pthread_t thread_id_two;
        pthread_create(&thread_id_one,NULL,helloworld_one,"helloworld");
        pthread_create(&thread_id_two,NULL,helloworld_two,"helloworld");
        pthread_join(thread_id_one,NULL);
        pthread_join(thread_id_two,NULL);
        return 0;
    }

    #include <stdio.h>
    #include <pthread.h>
    pthread_key_t key;
    
    void echomsg(void *t)
    {
        printf("destructor excuted in thread %u, param=%u
    ",pthread_self(),(int *)t);
    }
    
    void *child1(void *arg)
    {
        int i=10;
        int tid=pthread_self();
        printf("
    set key value %d in thread %u
    ",i,tid);
        pthread_setspecific(key,&i);
        printf("thread one sleep 2 until thread two finish
    ");
        sleep(2);
        printf("
    thread %u returns %d, add is %u
    ",tid,*(int *)pthread_getspecific(key),(int *)pthread_getspecific(key));
    
    }
    
    void *child2(void *arg)
    {
        int temp=20;
        int tid=pthread_self();
        printf("
    set key value %d in thread %u
    ",temp,tid);
        pthread_setspecific(key,&temp);
        sleep(1);
        printf("thread %u returns %d,add is %u
    ",tid,*(int *)pthread_getspecific(key),(int *)pthread_getspecific(key));
    }
    
    int main()
    {
        pthread_t tid1,tid2;
        pthread_key_create(&key,echomsg);
        pthread_create(&tid1,NULL,(void *)child1,NULL);
        pthread_create(&tid2,NULL,(void *)child2,NULL);
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
        return 0;
    }

    从运行结果来看,各线程对自己的私有数据操作互相不影响,虽然同名全局,但访问的内存空间并不是同一个。

  • 相关阅读:
    java算法---五家共井
    JAVA实用工具--javamail
    java基础篇---HTTP协议
    java基础解疑!!!
    java基础解疑!!
    jsp----标签编程(JSTL)
    jsp----EL表达式
    java基础篇---线程问题
    算法篇---java经典问题!!!
    java基础篇---注解(Annotation)
  • 原文地址:https://www.cnblogs.com/lakeone/p/3789584.html
Copyright © 2020-2023  润新知