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

freedom~~~~~~~~~~

文章分类

全部博文(79)

文章存档

2014年(10)

2013年(2)

2012年(13)

2011年(54)

分类: LINUX

2012-02-08 16:02:46

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <pthread.h>
  6. #include <semaphore.h>

  7. sem_t bin_sem;
  8. void *thread_function1(void *arg)
  9. {
  10.     printf("thread_function1--------------sem_wait\n");
  11.     sem_wait(&bin_sem);
  12.     printf("sem_wait\n");
  13.     while (1)
  14.     {
  15.     }
  16. }

  17. void *thread_function2(void *arg)
  18. {
  19.     printf("thread_function2--------------sem_post\n");
  20.     sem_post(&bin_sem);
  21.     printf("sem_post\n");
  22.     while (1)
  23.     {
  24.     }
  25. }



  26. int main()
  27. {
  28.     int res;
  29.     pthread_t a_thread;
  30.     void *thread_result;

  31.     res = sem_init(&bin_sem, 0, 0);
  32.     if (res != 0)
  33.     {
  34.         perror("Semaphore initialization failed");
  35.     }
  36.     printf("sem_init\n");
  37.     res = pthread_create(&a_thread, NULL, thread_function1, NULL);
  38.     if (res != 0)
  39.     {
  40.         perror("Thread creation failure");
  41.     }
  42.     printf("thread_function1\n");
  43.     sleep (5);
  44.     printf("sleep\n");
  45.     res = pthread_create(&a_thread, NULL, thread_function2, NULL);
  46.     if (res != 0)
  47.     {
  48.         perror("Thread creation failure");
  49.     }
  50.     while (1)
  51.     {
  52.     }
  53. }
阅读(780) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~