IO进程day7

1、思维导图

https://www.zhixi.com/view/bed0eee2

2、作业

#include 

char buf[]="1234567";
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;//互斥锁

void *A(void *a)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);//A上锁

		if(sem_wait((sem_t*)a)<0)
		{
			perror("sem_wait");
			return NULL;
		}

		int i=0,j=strlen(buf)-1;
		while(i
#include

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;

char buf[20];
int flag=0; //0打印  1输出

void *A(void *a)
{
	ssize_t r;
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(flag!=0)
			pthread_cond_wait(&cond1,&mutex);
		r=read(*((int *)a),buf,sizeof(buf));
		if(r==0)
			break;
		flag=1;
		pthread_cond_signal(&cond1);
		pthread_mutex_unlock(&mutex);
	}
	pthread_exit(NULL);
}

void *B(void *b)
{
	ssize_t w;
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(flag!=1)
			pthread_cond_wait(&cond1,&mutex);
		w=write(1,buf,sizeof(buf));
		if(w==0)
			break;
		pthread_cond_signal(&cond1);
		pthread_mutex_unlock(&mutex);
	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	pthread_t tid1,tid2;
	int fd=open(argv[1],O_RDONLY);

	pthread_create(&tid1,NULL,A,(void*)&fd);
	pthread_create(&tid2,NULL,B,(void*)&fd);

	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	close(fd);

	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond1);

	return 0;
}

你可能感兴趣的:(linux,c语言)