Chinaunix首页 | 论坛 | 博客
  • 博客访问: 360882
  • 博文数量: 79
  • 博客积分: 1270
  • 博客等级: 中尉
  • 技术积分: 1370
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-12 08:48
个人简介

freedom~~~~~~~~~~

文章分类

全部博文(79)

文章存档

2014年(10)

2013年(2)

2012年(13)

2011年(54)

分类: LINUX

2011-06-30 15:23:37

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<pthread.h>

  4. static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
  5. static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

  6. int g_flag=0;
  7. pthread_t tid1,tid2;
  8. void * thread1()
  9. {
  10.     printf("this is thread1\n");
  11.     printf("this is thread1,g_flag=%d,thread id is %u\n",g_flag,(unsigned int)pthread_self());
  12.     pthread_mutex_lock(&mutex);
  13.     if(g_flag==2)
  14.     {
  15.         g_flag=1;
  16.         pthread_cond_signal(&cond);                
  17.     }
  18.     g_flag=1;
  19.     pthread_mutex_unlock(&mutex);//不要写程unclock
  20.     printf("this is thread1,g_flag=%d,thread id is %u\n",g_flag,(unsigned int)pthread_self());
  21.     pthread_join(tid2,NULL);
  22.     printf("leave thread1\n");
  23.     pthread_exit(0);

  24. }

  25. void * thread2()
  26. {
  27.     printf("this is thread2\n");
  28.     printf("this is thread2,g_flag=%d,thread id is %u\n",g_flag,(unsigned int)pthread_self());
  29.     pthread_mutex_lock(&mutex);
  30.     if(g_flag==1)
  31.     {
  32.         g_flag=2;
  33.         pthread_cond_signal(&cond);                
  34.     }
  35.     g_flag=2;
  36.     pthread_mutex_unlock(&mutex);
  37.     printf("this is thread2,g_flag=%d,thread id is %u\n",g_flag,(unsigned int)pthread_self());
  38.     printf("leave thread2\n");
  39.     pthread_exit(0);

  40. }

  41. int main()
  42. {
  43.     int rc1=pthread_create(&tid1,NULL,thread1,NULL);
  44.     if(rc1!=0)
  45.     {
  46.         printf("can't create rc1\n");
  47.         return(-1);
  48.     }

  49.     int rc2=pthread_create(&tid2,NULL,thread2,NULL);
  50.     if(rc2!=0)
  51.     {
  52.         printf("can't create rc2\n");
  53.         return(-1);
  54.     }

  55.     pthread_cond_wait(&cond,&mutex);
  56.     printf("________________________leave main\n");
  57.     return 1;
  58. }
阅读(1367) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~