首页 > 编程语言 > 详细

线程间的同步----利用信号量来实现

时间:2015-04-27 21:47:58      阅读:201      评论:0      收藏:0      [点我收藏+]
#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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!