码迷,mamicode.com
首页 > 其他好文 > 详细

简单生产者与消费者同步解决方案

时间:2015-02-18 11:53:32      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

/*************************************************************************
    > File Name: producerAndconsumer.c
    > Author: wangzhicheng
    > Mail: 2363702560@qq.com 
    > Created Time: Wed 18 Feb 2015 11:22:02 AM WST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 16
char buffer[N];
int product;
sem_t sem_mutex;
sem_t sem_full;
sem_t sem_empty;
void *producer(void *arg) {
	static int index;
	while(1) {
		sem_wait(&sem_empty);
		sem_wait(&sem_mutex);
		buffer[index] = product;
		product++;
		index = (index + 1) & (N - 1);
		sem_post(&sem_mutex);
		sem_post(&sem_full);
		sleep(1);
	}
}
void *consumer(void *arg) {
	static int index;
	while(1) {
		sem_wait(&sem_full);
		sem_wait(&sem_mutex);
		printf("%d\n", buffer[index]);
		index = (index + 1) & (N - 1);
		sem_post(&sem_mutex);
		sem_post(&sem_empty);
		sleep(1);
	}
}
int main() {
	pthread_t pid_p, pid_c;
	sem_init(&sem_mutex, 0, 1);
	sem_init(&sem_full, 0, 0);
	sem_init(&sem_empty, 0, N);
	if(pthread_create(&pid_p, NULL, producer, NULL)) {
		perror("producer thread creating failed...!\n");
		exit(EXIT_FAILURE);
	}
	if(pthread_create(&pid_p, NULL, consumer, NULL)) {
		perror("consumer thread creating failed...!\n");
		exit(EXIT_FAILURE);
	}

	pthread_join(pid_p, NULL);
	pthread_join(pid_c, NULL);

//	sem_destory(&sem_mutex);
//	sem_destory(&sem_full);
//	sem_destory(&sem_empty);

	return 0;

}


技术分享

简单生产者与消费者同步解决方案

标签:

原文地址:http://blog.csdn.net/wangzhicheng1983/article/details/43876251

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!