首页 > 代码库 > thread_24

thread_24

#include <stdlib.h>#include <pthread.h>#include <stdio.h>#include <sched.h>#include<string.h>pthread_key_t key;void destructor(void *data) {      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);         printf("(%u)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);       printf("(%u)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()提前终止线程,也会调用撤销函数。*/

 

thread_24