C语言:操作系统临界区问题!
请高手用C写个临界区的程序代码给我看看,我自己试着写了写,可是感觉很垃,而且不对,实在没办法,想请教高手写个给我学习一下,最好是多进程的,并请给我说明是如何做到同步的,谢...
请高手用C写个临界区的程序代码给我看看,我自己试着写了写,可是感觉很垃,而且不对,实在没办法,想请教高手写个给我学习一下,最好是多进程的,
并请给我说明是如何做到同步的,谢谢了!!
我会追加100分的!!! 展开
并请给我说明是如何做到同步的,谢谢了!!
我会追加100分的!!! 展开
2个回答
展开全部
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define false 0
#define true 1
int flag[2];
int turn;
void P0()
{
while(true)
{
flag[0]=true;
turn = 1;
while(flag[1]&&turn==1)
;
printf ("P0 is in critical section.\n");
printf ("P0 is going to leave critical section.\n");
flag[0]=false;
printf ("P0 is out of critical section.\n");
}
}
void P1()
{
while(true)
{
flag[1]=true;
turn = 0;
while(flag[0]&&turn==0)
;
printf ("P1 is in critical section.\n");
printf ("P1 is going to leave critical section.\n");
flag[1]=false;
printf ("P1 is out of critical section.\n");
}
}
int main()
{
pthread_t pid0;
pthread_t pid1;
flag[0]=false;
flag[1]=false;
pthread_create(&pid0, NULL, (void*)P0, NULL);
pthread_create(&pid1, NULL, (void*)P1, NULL);
pthread_join(pid0, NULL);
pthread_join(pid1, NULL);
exit(0);
}
Linux系统下实现
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define false 0
#define true 1
int flag[2];
int turn;
void P0()
{
while(true)
{
flag[0]=true;
turn = 1;
while(flag[1]&&turn==1)
;
printf ("P0 is in critical section.\n");
printf ("P0 is going to leave critical section.\n");
flag[0]=false;
printf ("P0 is out of critical section.\n");
}
}
void P1()
{
while(true)
{
flag[1]=true;
turn = 0;
while(flag[0]&&turn==0)
;
printf ("P1 is in critical section.\n");
printf ("P1 is going to leave critical section.\n");
flag[1]=false;
printf ("P1 is out of critical section.\n");
}
}
int main()
{
pthread_t pid0;
pthread_t pid1;
flag[0]=false;
flag[1]=false;
pthread_create(&pid0, NULL, (void*)P0, NULL);
pthread_create(&pid1, NULL, (void*)P1, NULL);
pthread_join(pid0, NULL);
pthread_join(pid1, NULL);
exit(0);
}
Linux系统下实现
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询