20230804

1.创建2个线程,其中一个负责读取文件数据,另一个负责将读取的数据打印到终端上去,类似cat函数,读取完后结束2个线程。

#include <head.h>
#include <pthread.h>
#include <semaphore.h>

int fpr = 4;
char buf[128] = "";
ssize_t res;
int flag = 0;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *Atid(void *arg);
void *Atid(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(flag != 0)
		{
			pthread_cond_wait(&cond,&mutex);
		}
		res = read(fpr,buf,sizeof(buf));
		if(res == 0)
		{
			printf("resr = %ld\n",res);
			pthread_cond_signal(&cond);
			pthread_mutex_unlock(&mutex);
			pthread_exit(NULL);
		}
		flag = 1;
		pthread_cond_signal(&cond);
		pthread_mutex_unlock(&mutex);
	}
}

void *Btid(void *arg);
void *Btid(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(flag != 1)
		{
			pthread_cond_wait(&cond,&mutex);
		}
		if((write(1,buf,res)) < 0)
		{
			perror("write\n");
			return NULL;
		}
		if(res == 0)
		{
			printf("resw = %ld\n",res);
			pthread_exit(NULL);
		}
		flag = 0;
		pthread_cond_signal(&cond);
		pthread_mutex_unlock(&mutex);
	}
}


int main()
{
	if((fpr = open("/home/ubuntu/hqyj/HQYJ/IO/D4/p2.c",O_RDONLY)) < 0)
	{
		perror("open");
		return -1;
	}
	printf("Read文件 %d 打开成功\n",fpr);

	pthread_t tida;
	pthread_t tidb;
	if(pthread_create(&tida,NULL,Atid,NULL) != 0)
	{
		perror("preate_Atid");
		return -1;
	}
	printf("A创建成功\n");

	if(pthread_create(&tidb,NULL,Btid,NULL) != 0)
	{
		perror("preate_Atid");
		return -1;
	}
	printf("B创建成功\n");

	pthread_join(tida,NULL);
	pthread_join(tidb,NULL);

	close(fpr);

	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);

	return 0;
}

2.线程 循环打印1234567和7654321,要求1234567,7654321不能出现其他顺序

#include <head.h>
#include <pthread.h>
#include <semaphore.h>

char s1[] = "1234567";
pthread_mutex_t mutex;

void* Atid(void *arg);
void* Atid(void *arg)
{
	
	while(1)
	{

		printf("A %s\n",s1);
		if(sem_post((sem_t*)arg) < 0)//返回物体1
		{
			perror("sem_post");
			return NULL;
		}

	}
}

void* Btid(void *arg);//void* arg <==> void* sem
void* Btid(void *arg)
{
	int i;
	for(i=0;s1[i]!='\0';i++)
	{
	}
	printf("len = %d\n",i);

	while(1)
	{
		if((sem_wait((void*)arg)) < 0)//申请物体1
		{
			perror("sem_wait");
			return NULL;
		}
		for(int j=0;j<(i/2);j++)
		{
			char s = s1[j];
			s1[j] = s1[i-1-j];
			s1[i-1-j] = s;
		}

	}
}

int main()
{
	sem_t sem;
	if(sem_init(&sem,0,1) < 0)
	{
		perror("set_init");
		return -1;
	}
	pthread_t tida;
	pthread_t tidb;
	if(pthread_create(&tida,NULL,Atid,(void*)&sem) != 0)
	{
		printf("create error!\n");
		return -1;
	}
	printf("A创建成功!\n");


	if(pthread_create(&tidb,NULL,Btid,(void*)&sem) != 0)
	{
		printf("create error!\n");
		return -1;
	}
	printf("B创建成功!\n");


	pthread_join(tida,NULL);
	pthread_join(tidb,NULL);
	
	
	sem_destory(&sem);
	return 0;
}



        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值