码迷,mamicode.com
首页 > 其他好文 > 详细

thread_24

时间:2014-09-27 01:20:09      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   使用   ar   sp   div   

#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

标签:des   style   blog   color   io   使用   ar   sp   div   

原文地址:http://www.cnblogs.com/leijiangtao/p/3995850.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!