程序要求:
在main函数中,启动新线程后,我们从键盘中读取一些文本并把他们放到工作区work_area数组,通过信号量的控制进行字符的统计。sem_post增加信号量的值,sem_wait减少信号的值。
程序如下:
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <pthread.h>
- #include <semaphore.h>
- void *thread_func(void *arg);
- sem_t bin_sem;
- char work_area[1000];
- int main(int argc,char *argv[])
- {
- int res;
- pthread_t a_thread;
- void *pthread_result;
- res = sem_init(&bin_sem,0,0);
- if(res!=0)
- {
- perror("semaphore initialization error");
- exit(-1);
-
- }
- res = pthread_create(&a_thread, NULL, thread_func, NULL);
- if(res!=0)
- {
- perror("pthread create error");
- exit(-1);
-
- }
- printf("please input sometext.enter 'end'to finish\n");
- while(strncmp("end",work_area,3) != 0)
- {
-
- fgets(work_area, 1000, stdin);
- sem_post(&bin_sem);
- }
- printf("\nwaitfor thread finish...\n");
- res = pthread_join(a_thread, &pthread_result);
- if(res != 0)
- {
-
- perror("join error");
- exit(-1);
- }
- printf("thread joined\n");
- sem_destroy(&bin_sem);
- exit(0);
- }
- void *thread_func(void *arg)
- {
- sem_wait (&bin_sem);
- while(strncmp("end", work_area, 3)!=0)
- {
- printf("you input %d character \n",strlen(work_area)-1);
- sem_wait(&bin_sem);
-
- }
- pthread_exit(NULL);
- }
阅读(1490) | 评论(0) | 转发(0) |