#include <stdlib.h> #include <pthread.h> #include <stdio.h> #include <sched.h> #include<string.h> pthread_key_t key; void destructor(void *data) //如果创建该键时指定了destructor 函数,则该线程终止时,系统会调用destructor 函数,传进的参数是绑定的值。 { if(data != NULL) free(data); printf("thread (%u) do free key\n", (unsigned)pthread_self()); } void print_key(void) { char *p; p = (char *)pthread_getspecific(key); printf("(%u) key_value:%s\n", (unsigned)pthread_self(), p); } void *thread1(void *arg) { printf("start thread (%u)\n", (unsigned)pthread_self()); char * p = malloc(7*sizeof(char)); memset(p, ‘a‘, 6); p[6] = ‘\0‘; pthread_setspecific(key, p);//key绑定的值为p printf("(%lu)setkey:%s\n", pthread_self(), p); print_key(); printf("thread (%u) end\n", pthread_self()); } void *thread2(void *arg) { printf("start thread (%u)\n", (unsigned)pthread_self()); char * p = malloc(7*sizeof(char)); memset(p, ‘c‘, 6); p[6] = ‘\0‘; pthread_setspecific(key, p);//key绑定的值为p printf("(%lu)setkey:%s\n", pthread_self(), p); print_key(); printf("thread (%u) end\n", pthread_self()); } int main(int argc, char *argv[]) { pthread_t t1, t2, t3; pthread_key_create(&key, destructor); pthread_create(&t1, NULL, thread1, NULL); pthread_create(&t2, NULL, thread2, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("main end\n"); return 0; } //执行结果如下 1.在每个线程结束后系统会执行注册的撤销函数。 2.如果使用pthread_exit()提前终止线程,也会调用撤销函数。
时间: 2024-10-12 15:52:05