练习用信号量的方式,创建两个线程A B1. A线程读取文件中的内容2. B线程打印A读取到的内容到终端,3.全部打印完毕后,结束进程;4.现象类似cat个文件

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
#define MAX 100000
char c[MAX]="";
struct file
{
	int fd;
    int size;	
};
 sem_t sem;
void *callback1(void* arg)
{
	int i=0;
    lseek(((struct file*)arg)->fd, 0,SEEK_SET);
	for(i=0;i<((struct file*)arg)->size;i++)
	{
 		sem_wait(&sem);
		ssize_t p;
		p=read(((struct file *)arg)->fd,&c[i],1);
	   printf("%c",c[i]);
		sem_post(&sem);
	}
	
}
void *callback2(void* arg)
{
	if(strlen(c))
	{
	int i=0;
   for(i=0;i<((struct file*)arg)->size;i++)
   {
	   sem_wait(&sem);
	   printf("%c",c[i]);
	   sem_post(&sem);
   }
   }
	pthread_exit(NULL);
}

int main(int argc, const char *argv[])
{
	if(sem_init(&sem,0,1)!=0)
    {
		printf("申请失败");
		return -1;
	}
   int fd=open(argv[1],O_RDONLY);
   off_t size=lseek(fd,0,SEEK_END);
	printf("size%ld",size);
	if(fd<0)
	{
		perror("open");
	}
	struct file p;
	p.fd=fd;
	p.size=size;
    pthread_t sid1;
    if(pthread_create(&sid1,NULL,callback1,(void*)&p)!=0)
	{
		perror("pthread_create");
		return -1;
	}
    pthread_t sid2;
    if(pthread_create(&sid2,NULL,callback2,(void*)&p)!=0)
	{
		perror("pthread_create");
		return -1;
	}
	pthread_join(sid1,NULL);
	pthread_join(sid2,NULL);
    sem_destroy(&sem);
	close(fd);
   return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值