什么是临界区?

什么是临界区?,第1张

临界区是指不允许多个并发进程交叉执行的一段程序。它是由于不同并发进程的程序段共享公用数据或者公用数据变量而引起的。所以又被称为访问公用数据的那段程序。没事可以多看看黑马程序员官网的免费视频,这些问题一套基础视频都可以解决。

t

#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系统下实现


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/8791708.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-21
下一篇2023-04-21

发表评论

登录后才能评论

评论列表(0条)

    保存