prg10_6.c

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

C
78
字号
#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>
#include <fcntl.h>

#define	NBUFF	10
#define	SEM_MUTEX	"/tmp/ftest1.t"
#define	SEM_NEMPTY	"/tmp/ftest2.t"
#define	SEM_NSTORED	"/tmp/ftest3.t"
#define	FILE_MODE	(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

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]);
	shared.mutex = sem_open(SEM_MUTEX,O_CREAT | O_EXCL,FILE_MODE,1);
	shared.nempty = sem_open(SEM_NEMPTY,O_CREAT | O_EXCL,FILE_MODE,NBUFF);
	shared.nstored = sem_open(SEM_NSTORED,O_CREAT | O_EXCL,FILE_MODE,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_unlink(SEM_MUTEX);
	sem_unlink(SEM_NEMPTY);
	sem_unlink(SEM_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 + -
显示快捷键?