#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define true 1
#define false 0
int turn;
int flag[2];
int cs=0;
void *p0()
{
while(true)
{
flag[0]=true;
while(flag[1])
{
if(turn==1)
flag[0]=false;
while(turn==1);
flag[0]=true;
}
cs+=1;
printf("p0进程:cs的值为:%d\n",cs);
turn=1;
flag[0]=false;
sleep(3);
}
}
void *p1()
{
while(true)
{
flag[1]=true;
while(flag[0])
{
if(turn==0)
flag[1]=false;
while(turn==0);
flag[1]=true;
}
cs+=2;
printf("p1进程:cs的值为:%d\n",cs);
turn=0;
flag[1]=false;
sleep(3);
}
}
int main()
{
turn=0;
flag[0]=true;
flag[1]=false;
int t1,t2;
pthread_t s1,s2;
t1=pthread_create(&s1,NULL,p0,NULL);
if(t1!=0)
{
printf("p0进程创建失败!");
exit(1);
}
t2=pthread_create(&s2,NULL,p1,NULL);
if(t2!=0)
{
printf("p1进程创建失败!");
exit(1);
}
pthread_join(s1,NULL);
pthread_join(s2,NULL);
return 0;
}
Dekker算法
最新推荐文章于 2022-11-16 10:54:01 发布