zhjl616 发表于 2012-10-05 13:18

关于线程特定数据共享全局变量的一个问题

我有一个问题,线程特定数据怎么理解,我看了些小程序,差不多是不是这个意思,进程有一个key,然后每个线程给进程的这个key设定一个值(指针),各个线程的值是独立的,于是我看了下下面这个程序,表示不淡定了,共享全局变量的问题。
#include <stdio.h>
#include <pthread.h>

int my_errno = 0;
pthread_key_t key;

void *thread2(void *arg)
{
        my_errno = 2;
        pthread_setspecific(key, &my_errno);
       
        printf("thread2: %u; pkey address: %p; pkey value: %d, my_errno = %d, my_errno address = %p\n",
                (unsigned int)pthread_self(), (int *)pthread_getspecific(key),
                *((int *)pthread_getspecific(key)), my_errno, &my_errno);
}

void *thread1(void *arg)
{
        my_errno = 1;
    pthread_setspecific(key, &my_errno);

        printf("thread2: %u; pkey address: %p; pkey value: %d, my_errno = %d, my_errno address = %p\n",
                (unsigned int)pthread_self(), (int *)pthread_getspecific(key),
                *((int *)pthread_getspecific(key)), my_errno, &my_errno);
}

int main(void)
{
    pthread_t thid1, thid2;

    printf("main thread begins running, my_errno=%d, my_errno address = %p\n",my_errno, &my_errno);
    pthread_key_create(&key, NULL);
       
    pthread_create(&thid1, NULL, thread1, NULL);
        pthread_create(&thid2, NULL, thread2, NULL);
        sleep(2);
    pthread_key_delete(key);
    printf("main thread exit\n");
    return 0;
}
程序输出:

main thread begins running, my_errno=0, my_errno address = 0x8049adc
thread2: 3067120496; pkey address: 0x8049adc; pkey value: 2, my_errno = 2, my_errno address = 0x8049adc
thread2: 3077610352; pkey address: 0x8049adc; pkey value: 1, my_errno = 1, my_errno address = 0x8049adc
main thread exit

我发现共享的全局变量的地址是一样的 0x8049b0c,但是值不一样,既然是特定数据,我的理解是每个线程为此数据单独开辟一个空间存储,相当于存储副本,但是事实好像不是这样子,麻烦高手帮忙解释一下吧。

linux_c_py_php 发表于 2012-10-05 14:58

是第一个线程执行完退出了, 第二个线程才执行的吧.

楼主想多了.

fdl19881 发表于 2012-10-05 15:30

{:3_198:} {:3_198:} {:3_198:}
回复 2# linux_c_py_php


   

linux_c_py_php 发表于 2012-10-05 15:49

汗, 你也在.

fdl19881 发表于 2012-10-05 15:30 static/image/common/back.gif
回复 2# linux_c_py_php

fdl19881 发表于 2012-10-05 15:53

回复 4# linux_c_py_php

其实我已经有几个月没来CU了,,看你在csdn那说了,才来围观下哈,,,
   

linux_c_py_php 发表于 2012-10-05 16:00

我才来几周, 不活跃没东西学啊.

fdl19881 发表于 2012-10-05 15:53 static/image/common/back.gif
回复 4# linux_c_py_php

其实我已经有几个月没来CU了,,看你在csdn那说了,才来围观下哈,,,

梦醒潇湘love 发表于 2012-12-28 11:20

线程私有数据??
页: [1]
查看完整版本: 关于线程特定数据共享全局变量的一个问题