第一个线程锁

 

#include <pthread.h>
#include <stdio.h>
#include <windows.h>
typedef struct message {
	int a;
	int user;
} message;

void* show(void* a) {
	
//	CreateProcess()
	
//pthread_mutex_unlock(&mut);
	
	int* b = (int *)a;
	
	while (1) {
//		printf("k\n");
//		(*b) += 1;
		
		// 数据打印测试共享成功后测试开启关闭功能
//		if(*b==0){
//			*b=1;
//		}
		
		
//		Sleep(500);
//		if(*b==1){
//			*b=0;
//		}
		
		// 等待,直到执行为止
		while (*b == 1) {
			printf("A发现数据被占用\n");
//			Sleep(50);
			
			// 模拟高频使用
//			Sleep(5);
//			Sleep(135);
			Sleep(235);
		}
		
		
		if (*b == 0) {
			*b = 1;
		}
		
		
		printf("A写入中(占用中)\n");
		Sleep(300);
		
		*b = 0;
		printf("A写入完成(占用完成)\n");
		
//		Sleep(200);
//		Sleep(1200);
		
		//休眠时间短,模拟高频使用数据
//		Sleep(120);
		Sleep(320);
	}
}


void* showv2(void* a) {
	int* b = (int*)a;
	
	while (1) {
//		printf("p\n");
		printf("%d\n", *b);
//		printf("%d\n",*a);
		
//		if (*b == 1) {
//			printf("ok\n");
//		} else if (*b == 0) {
//			printf("no\n");
//		}
		
		while (*b == 1) {
			printf("B发现数据被占用\n");
//			Sleep(50);
			Sleep(150);
		}
		
		if (*b == 0) {
			*b = 1;
		}
		
		printf("B写入中(占用中)\n");
		// 模拟长时间使用
		Sleep(300);
		*b = 0;
		printf("B写入完成(占用完成)\n");
		
//		Sleep(100);
		Sleep(300);
	}
}

void* showv3(void* msg) {
	message* m = (message*)msg;
	
	while (1) {
		
		while ((*m).a == 1) {
			printf("占用者:%d\n", (*m).user);
			Sleep(100);
		}
		
		(*m).a = 1;
		(*m).user = 33;
		printf("A写入中(占用中)\n");
		Sleep(300);
		
		
		printf("A写入完成(占用完成)\n");
		// 标记为没有被占用
		(*m).a=0;
		Sleep(200);
	}
}

void* showv4(void* msg) {
	message* m = (message*)msg;
	
	while (1) {
		
		// 等待
		while ((*m).a == 1) {
			printf("占用者:%d\n", (*m).user);
			Sleep(100);
		}
		
		// 开始占用
		(*m).a = 1;
		(*m).user = 22;
		printf("B写入中(占用中)\n");
		Sleep(300);
		
		
		printf("B写入完成(占用完成)\n");
		// 标记为没有被占用
		(*m).a=0;
		Sleep(200);
	}
}



int main() {
	int* a = new int();
//	*a = 10;
//	*a = 1;
	*a = 0;
	
	
	message msg;
//	message* msg =new message;
	
//	msg->a = 0;
//	msg->user = 0;
	
	msg.a = 0;
	msg.user = 0;
	
	pthread_t p;
	pthread_t p2;
//	pthread_create(&p,NULL,show,NULL);
//	pthread_create(&p,NULL,showv2,NULL);
	
//	pthread_create(&p, NULL, show, (void*)a);
//	pthread_create(&p, NULL, showv2, (void*)a);
	
//	while (1) {
//		printf("main------监测情况-------%d\n", *a);
//		Sleep(1000);
//	}
	
	
	
	pthread_create(&p, NULL,showv3,(void*)&msg);
	pthread_create(&p, NULL,showv4,(void*)&msg);
	
	
	while(1){
		printf("main------监测情况----%d---%d\n",msg.a, msg.user);
		Sleep(1000);
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值