#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);
}
}