IO线程作业

本文介绍了一个使用信号量实现线程间同步的例子。通过两个线程分别完成文件读取与打印的任务,展示了如何利用信号量机制确保操作的有序进行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>

//信号量
sem_t sem1,sem2;
char str[20];
int res;


void* callBack1(void *arg)
{
	int fd=open("./01_pthread_exit.c",O_RDONLY);
	if(fd<0)
	{
		perror("open");
		return NULL;
	}
	while(1)
	{
		sem_wait(&sem1);
		res=read(fd,str,sizeof(str));
		if(res==0)
		{
			printf("文件读取完毕\n");
			sem_post(&sem2);
			break;
		}
		sem_post(&sem2);
	}
	close(fd);
	pthread_exit(NULL);
}

void* callBack2(void *arg)
{
	while(1)
	{
		sem_wait(&sem2);
		write(1,str,res);
		if(res==0)
		{
			printf("文件打印完毕\n");
			sem_post(&sem1);
			break;
		}
		sem_post(&sem1);
	}
}

int main(int argc, const char *argv[])
{
	//创建并初始化信号量
	if(sem_init(&sem1,0,1)<0)
	{
		perror("sem_init");
		return -1;
	}
	if(sem_init(&sem2,0,0)<0)
	{
		perror("sem_init");
		return -1;
	}

	pthread_t tid_front,tid_end;
	//创建两个分支线程

	//读取文件内容进程
	if(pthread_create(&tid_front,NULL,callBack1,NULL)!=0)
	{
		perror("pthread_create");
		return -1;
	}

	//打印文件内容进程
	if(pthread_create(&tid_end,NULL,callBack2,NULL)!=0)
	{
		perror("pthread_create");
		return -1;
	}

	//主线程阻塞等待分支进程退出
	pthread_join(tid_front,NULL);
	pthread_join(tid_end,NULL);

	//销毁信号量
	sem_destroy(&sem1);
	sem_destroy(&sem2);



	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值