共享全局变量实例:
#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; }
#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; }
从运行结果来看,各线程对自己的私有数据操作互相不影响,虽然同名全局,但访问的内存空间并不是同一个。