prg10_8.c

来自「配套光盘网络编程进程间的通信,网络编程进程间的通信是一本很经典的好书」· C语言 代码 · 共 73 行

C
73
字号
#include <stdlib.h>
#include <semaphore.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/stat.h>

#define	NBUFF	10

int  nitems;
struct {
	int buff[NBUFF];
	sem_t  mutex,nempty,nstored;
}shared;

void *produce(void *),*consume (void *);
int main(int argc, char **argv)
{
	pthread_t  tid_produce,tid_consume;
	if (argc !=2)
	{
		printf("usage:%s <#items>",argv[0]);
		exit(0);
	}
	nitems = atoi(argv[1]);
	sem_init(&shared.mutex,0,1);
	sem_init(&shared.nempty,0,NBUFF);
	sem_init(&shared.nstored,0,0);

	pthread_setconcurrency(2);
	pthread_create(&tid_produce,NULL,produce,NULL);
	pthread_create(&tid_consume,NULL,consume,NULL);
	
	pthread_join(tid_produce,NULL);
	pthread_join(tid_consume,NULL);
	
	sem_destroy(&shared.mutex);
	sem_destroy(&shared.nempty);
	sem_destroy(&shared.nstored);
	exit(0);
}

void *produce(void *arg)
{
	int  i;
	for(i=0; i<nitems;i++)
	{
		sem_wait(&shared.nempty);
		sem_wait(&shared.mutex);
		shared.buff[i%NBUFF] = i;
		sem_post(&shared.mutex);
		sem_post(&shared.nstored);
	}
	return (NULL);
}

void *consume(void *arg)
{
	int  i;
	for(i=0; i<nitems; i++)
	{
		sem_wait(&shared.nstored);
		sem_wait(&shared.mutex);
		if (shared.buff[i%NBUFF] != i)
		  printf("buff[%d] = %d\n",i,shared.buff[i%NBUFF]);
		sem_post(&shared.mutex);
		sem_post(&shared.nempty);
	}
	return (NULL);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?