标签:
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <semaphore.h> sem_t bin_sem; void *thread_funtion(void *arg); char work_area[1024]; int main() { pthread_t a_thread; int res; void *thread_result; res = sem_init(&bin_sem, 0, 0); if(res != 0) { perror("初始化信号量失败"); exit(EXIT_FAILURE); } res = pthread_create(&a_thread, NULL, thread_funtion, NULL); if(res != 0) { perror("线程创建失败"); exit(EXIT_FAILURE); } printf("请输入要传送的信息,输入'end'退出\n"); while(strncmp("end", work_area, 3) != 0) { fgets(work_area, 1024, stdin); sem_post(&bin_sem); // 将信号量加1 } printf("\n等待线程结束...\n"); res = pthread_join(a_thread, &thread_result); // 等待线程结束 if (res != 0) { // 判断结束线程是否有错误 perror("线程结束失败"); exit(EXIT_FAILURE); } printf("线程结束\n"); sem_destroy(&bin_sem); // 清除信号量 // 清除信号量 exit(EXIT_SUCCESS); } void *thread_funtion(void *arg) { sem_wait(&bin_sem); // 等待信号量变化,将信号量减1 while(strncmp("end", work_area, 3) != 0) { // 判断收到的信息是否是“end” printf("收到%lu个字符\n", strlen(work_area) - 1); // 输出收到信息的字符数量 sem_wait(&bin_sem); // 等待信号量变化,将信号量减1 } pthread_exit(NULL); // 结束线程 }
标签:
原文地址:http://blog.csdn.net/u010470972/article/details/45315485