码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-06-19 06:19:28      阅读:494      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   http   

共享全局变量实例:

#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\n",argc);
    key=10;
    printf("key=%d, the child is %u\n",key,pthread_self());
    return 0;
}

void *helloworld_two(char *argc)
{
    printf("the message is %s\n",argc);
    sleep(1);
    printf("key=%d, the child is %u\n",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;
}

bubuko.com,布布扣

#include <stdio.h>
#include <pthread.h>
pthread_key_t key;

void echomsg(void *t)
{
    printf("destructor excuted in thread %u, param=%u\n",pthread_self(),(int *)t);
}

void *child1(void *arg)
{
    int i=10;
    int tid=pthread_self();
    printf("\nset key value %d in thread %u\n",i,tid);
    pthread_setspecific(key,&i);
    printf("thread one sleep 2 until thread two finish\n");
    sleep(2);
    printf("\nthread %u returns %d, add is %u\n",tid,*(int *)pthread_getspecific(key),(int *)pthread_getspecific(key));

}

void *child2(void *arg)
{
    int temp=20;
    int tid=pthread_self();
    printf("\nset key value %d in thread %u\n",temp,tid);
    pthread_setspecific(key,&temp);
    sleep(1);
    printf("thread %u returns %d,add is %u\n",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;
}

bubuko.com,布布扣

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

线程共享全局变量和私有全局变量,布布扣,bubuko.com

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

标签:des   style   class   blog   code   http   

原文地址:http://www.cnblogs.com/lakeone/p/3789584.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!