IO作业 0510

1. 用条件变量的方式实现:现有ID号为a b c的三个线程,每个线程的任务都是循环打印自己id号,要求打印的顺序为abc

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond,cond1,cond2= PTHREAD_COND_INITIALIZER;
int flag=0;
void* callback(void *arg)
{
	while(1)
	{
		///临界代码///
		pthread_mutex_lock(&mutex);
		if(flag!=0)
		{
			pthread_cond_wait(&cond,&mutex);
		}
		printf("a\n");
		flag = 1;
		pthread_cond_signal(&cond1);
		pthread_mutex_unlock(&mutex);
		///临界代码///
	}
}
void* callback1(void *arg)
{
	while(1)
	{
		///临界代码///
		pthread_mutex_lock(&mutex);
		if(flag!=1)
		{
			pthread_cond_wait(&cond1,&mutex);
		}
		printf("b\n");
		flag=2;
		pthread_cond_signal(&cond2);
		pthread_mutex_unlock(&mutex);
		///临界代码///
	}
}
void* callback2(void *arg)
{
	while(1)
	{
		///临界代码///
		pthread_mutex_lock(&mutex);
		if(flag!=2)
		{
			pthread_cond_wait(&cond2,&mutex);
		}
		printf("c\n");
		flag = 0;
		pthread_cond_signal(&cond);
		pthread_mutex_unlock(&mutex);
		///临界代码///
	}
}
int main(int argc, const char *argv[])
{
	pthread_t tid,tid1,tid2;
	if(pthread_create(&tid,NULL,callback,NULL)!=0)
	{
		printf("error\n");
		return -1;
	}
	if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
	{
		printf("error1\n");
		return -1;
	}
	if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
	{
		printf("error\n");
		return -1;
	}
	pthread_join(tid1,NULL);
	pthread_mutex_destroy(&mutex);
	return 0;
}

2.创建两个线程,实现将一个文件的内容打印到终端上,类似cat一个文件
一个线程读取文件中的内容
另一个线程将读取到的内容打印到终端上。

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
sem_t sem1,sem2;
int fd_r;
char c;
int res=0;
void *callback(void *arg)
{
	while(1)
	{
		sem_wait(&sem1);
		res=read(fd_r,&c,1);
		if(res<=0)
			break;
		sem_post(&sem2);
	}
	pthread_exit(NULL);
}
void *callback1(void *arg)
{
	while(1)
	{
		sem_wait(&sem2);
		if(res<=0)
			break;
		printf("%c",c);
		sem_post(&sem1);
	}
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	sem_init(&sem1,0,1);
	sem_init(&sem2,0,0);
	fd_r=open("./test.c",O_RDONLY);
	pthread_t tid,tid1;
	if(pthread_create(&tid,NULL,callback,NULL)!=0)
	{
		printf("tid error\n");
		return -1;
	}
	if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
	{
		printf("tid1 error\n");
		return -1;
	}
	pthread_join(tid,NULL);
	sem_destroy(&sem1);
	sem_destroy(&sem2);
	close(fd_r);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值