7.19作业

第一题:测试错误检查锁和递归锁是否会造成死锁状态

pthread_mutex_t at1;
pthread_mutex_t at2;
void* run(void* data)
{
	while(1)
	{
		pthread_mutex_lock(&at2);
		printf("2\n");
	}
}
int main(int argc, const char *argv[])
{
	pthread_mutexattr_t attrmutex;
	pthread_mutexattr_init(&attrmutex);
	//pthread_mutexattr_settype(&attrmutex,PTHREAD_MUTEX_RECURSIVE_NP);
	pthread_mutexattr_settype(&attrmutex,PTHREAD_MUTEX_ERRORCHECK_NP);
 
	pthread_mutex_init(&at1,&attrmutex);
	pthread_mutex_init(&at2,&attrmutex);
	pthread_mutexattr_destroy(&attrmutex);
 
	pthread_t thid;
	pthread_create(&thid,0,run,0);
	pthread_detach(thid);
 
	while(1)
	{
		pthread_mutex_lock(&at1);
		printf("1\n");
	}
	return 0;
}

第二题:有2条隧道,一条快速隧道,一条普通隧道。有5列火车,3列复兴号,2列绿皮扭扭车 要求,复兴号2条隧道都能走,绿皮车只能走普通隧道,模拟火车过隧道的场景

pthread_mutex_t m1;
pthread_mutex_t m2;

void* run1(void* arg)
{
	while(1){
		pthread_mutex_lock(&m1);
		printf("绿皮车占据了慢速隧道\n");
		sleep(1);
		pthread_mutex_unlock(&m1);
		usleep(100000);
	}
}
void* run2(void* arg)
{
	while(1){
		int i=rand()%2+1;
		if(i==1){
			int res=pthread_mutex_trylock(&m1);
			if(res!=0)continue;
			printf("高铁占据了慢速隧道\n");
			sleep(2);
			pthread_mutex_unlock(&m1);
		}else{
			pthread_mutex_lock(&m2);
			printf("高铁占据了快速隧道\n");
			sleep(2);
			pthread_mutex_unlock(&m2);
		}
	}
}

int main(int argc, const char *argv[])
{
	srand(time(0));
	pthread_mutex_init(&m1,0);
	pthread_mutex_init(&m2,0);

	pthread_t id1,id2;
	pthread_create(&id1,0,run1,0);
	pthread_create(&id2,0,run2,0);

	pthread_join(id1,0);
	pthread_join(id2,0);
	return 0;
}

第三题:创建2个线程,一个线程负责向文件中写入数据,一个线程负责从文件中读取数据并输出

pthread_mutex_t m1;
pthread_mutex_t m2;

void* run1(void* arg)
{
	while(1){
		pthread_mutex_lock(&m1);
		FILE* wfp=fopen("./1.c","w");
		char buf[64]={0};
		printf("please enter:");
		scanf("%s",buf);
		while(getchar()!=10);
		fwrite(buf,64,1,wfp);
		fclose(wfp);
		pthread_mutex_unlock(&m2);
	}
}
void* run2(void* arg)
{
	while(1){
		pthread_mutex_lock(&m2);
		FILE* rfp=fopen("./1.c","r");
		char buf[64]={0};
		fread(buf,64,1,rfp);
		printf("read=%s\n",buf);
		fclose(rfp);
		pthread_mutex_unlock(&m1);
	}
}

int main(int argc, const char *argv[])
{
	pthread_mutex_init(&m1,0);

	pthread_mutex_init(&m2,0);
	pthread_mutex_lock(&m2);

	pthread_t id1,id2;
	pthread_create(&id1,0,run1,0);
	pthread_create(&id2,0,run2,0);
	pthread_join(id1,0);
	pthread_join(id2,0);
	return 0;
}

思维导图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值