Chinaunix首页 | 论坛 | 博客
  • 博客访问: 237857
  • 博文数量: 35
  • 博客积分: 791
  • 博客等级: 军士长
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-05 16:56
文章分类
文章存档

2013年(7)

2012年(28)

我的朋友

分类: 嵌入式

2012-10-04 11:32:50

程序要求:
在main函数中,启动新线程后,我们从键盘中读取一些文本并把他们放到工作区work_area数组,通过信号量的控制进行字符的统计。sem_post增加信号量的值,sem_wait减少信号的值。
程序如下:

点击(此处)折叠或打开

  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. void *thread_func(void *arg);
  8. sem_t bin_sem;
  9. char work_area[1000];


  10. int main(int argc,char *argv[])
  11. {
  12.     int res;
  13.     pthread_t a_thread;
  14.     void *pthread_result;

  15.     res = sem_init(&bin_sem,0,0);
  16.     if(res!=0)
  17.     {
  18.         perror("semaphore initialization error");
  19.         exit(-1);
  20.     
  21.     }

  22.     res = pthread_create(&a_thread, NULL, thread_func, NULL);
  23.     if(res!=0)
  24.     {
  25.         perror("pthread create error");
  26.         exit(-1);
  27.     
  28.     }

  29.     printf("please input sometext.enter 'end'to finish\n");
  30.     while(strncmp("end",work_area,3) != 0)
  31.     {
  32.     
  33.         fgets(work_area, 1000, stdin);
  34.         sem_post(&bin_sem);

  35.     }
  36.     printf("\nwaitfor thread finish...\n");
  37.     res = pthread_join(a_thread, &pthread_result);
  38.     if(res != 0)
  39.     {
  40.     
  41.         perror("join error");
  42.         exit(-1);

  43.     }

  44.     printf("thread joined\n");
  45.     sem_destroy(&bin_sem);
  46.     exit(0);
  47. }


  48. void *thread_func(void *arg)
  49. {
  50.     sem_wait (&bin_sem);
  51.     while(strncmp("end", work_area, 3)!=0)
  52.     {
  53.         printf("you input %d character \n",strlen(work_area)-1);
  54.         sem_wait(&bin_sem);
  55.     
  56.     }
  57.     pthread_exit(NULL);

  58. }


阅读(1444) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~