- 論壇徽章:
- 0
|
我有一個(gè)問題,線程特定數(shù)據(jù)怎么理解,我看了些小程序,差不多是不是這個(gè)意思,進(jìn)程有一個(gè)key,然后每個(gè)線程給進(jìn)程的這個(gè)key設(shè)定一個(gè)值(指針),各個(gè)線程的值是獨(dú)立的,于是我看了下下面這個(gè)程序,表示不淡定了,共享全局變量的問題。
#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
我發(fā)現(xiàn)共享的全局變量的地址是一樣的 0x8049b0c,但是值不一樣,既然是特定數(shù)據(jù),我的理解是每個(gè)線程為此數(shù)據(jù)單獨(dú)開辟一個(gè)空間存儲(chǔ),相當(dāng)于存儲(chǔ)副本,但是事實(shí)好像不是這樣子,麻煩高手幫忙解釋一下吧。 |
|