首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。