zoukankan      html  css  js  c++  java
  • 线程共享全局变量和私有全局变量

    共享全局变量实例:

    #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;
    }

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

  • 相关阅读:
    用FileSystemWatcher监视文件系统
    生成随机汉字验证码
    MySQL学习笔记二
    python高级学习笔记
    boost bind 表达式中的是值语义还是指针语义?
    容器与适配器的个人总结
    subversion linux使用方法
    boost asio(初学示例)
    MySQL学习笔记一
    subversion 命令
  • 原文地址:https://www.cnblogs.com/lakeone/p/3789584.html
Copyright © 2011-2022 走看看