8.4作业

用信号量的方式实现打印1234567后打印7654321循环交替打印。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<head.h>
char buf[]="1234567";
sem_t sem;
void *callBack1(void *arg)
{
	int i=0;
	int s=strlen(buf)-1;
		while(i<s)
		{
			int t=buf[i];
			buf[i]=buf[s];
			buf[s]=t;
			i++;s--;
		}
	pthread_exit(NULL);
}
void *callBack2(void *arg)
{
		printf("%s\n",buf);
		sem_post(&sem);
	pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
	sem_init(&sem,0,1);
	while(1)
	{
	pthread_t pid1,pid2;
		sem_wait(&sem);
	if(pthread_create(&pid2,NULL,callBack2,NULL)!=0)
	{
		fprintf(stderr,"failed __%d__\n",__LINE__);
		return -1;
	}

	pthread_detach(pid2);
		sem_post(&sem);
		sem_wait(&sem);
	if(pthread_create(&pid1,NULL,callBack1,NULL)!=0)
	{
		fprintf(stderr,"failed __%d__\n",__LINE__);
		return -1;
	}
	pthread_join(pid1,NULL);
	}
	sem_destroy(&sem);
	return 0;
}

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

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<head.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
int flag=0;
void *callBack1(void*arg)
{
	int fd=open("./10.c",O_RDONLY);
	if(fd<0)
	{
		ERR_MSG("open");
		return NULL;
	}
	lseek(fd,0,SEEK_SET);
	char c;
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(flag!=0)
			pthread_cond_wait(&cond,&mutex);
		ssize_t res=read(fd,&c,1);
		if(res==0)
		{
			pthread_mutex_unlock(&mutex);
			break;
		}
		*(char*)arg=c;
		flag=1;
		pthread_cond_signal(&cond);
		pthread_mutex_unlock(&mutex);
	}
	pthread_exit(NULL);
}
void *callBack2(void*arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(flag!=1)
			pthread_cond_wait(&cond,&mutex);
		char c=*(char*)arg;
		printf("%c",c);
		flag=0;
		pthread_cond_signal(&cond);
		pthread_mutex_unlock(&mutex);
	}
	pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
	pthread_t tid1,tid2;
	char tmp_c=-1;
	if(pthread_create(&tid1,NULL,callBack1,(void*)&tmp_c)!=0)
	{
		fprintf(stderr,"failed __%d__\n",__LINE__);
		return -1;
	}
	if(pthread_create(&tid2,NULL,callBack2,(void*)&tmp_c)!=0)
	{
		fprintf(stderr,"failed __%d__\n",__LINE__);
		return -1;
	}
	pthread_join(tid1,NULL);
	pthread_cancel(tid2);
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值