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

/*************************************************************************
    > 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;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值