I'm studying the operating system and the program that Decker wrote for his third attempt to Mutual Exclusion I wrote my code in C ++ in Visual Studio, the code is below, but I wonder how these two threads are still in the critical area at the same time? The output of the program is below
#include<iostream>
#include<conio.h>
#include<thread>
using namespace std;
bool flag0 = false;
bool flag1 = false;
void p1()
{
flag0 = true;
while (flag1);
for (int i = 1; i <= 10; i++)
cout << "p1 : " << i << endl;
flag0 = false;
}
void p2()
{
flag1 = true;
while (flag0);
for (int i = -1; i >= -10; i--)
cout << "p2 : " << i << endl;
flag1 = false;
}
int main()
{
thread t1(p1);
thread t2(p2);
t1.join();
t2.join();
_getch();
return 0;
}
Output:
p1 : p2 : -11
p2 : p1 : 2
p1 : 3
p1 : 4
p1 : 5
p1 : 6
-2
p2 : -3
p2 : -4
p2 : -5
p2 : -6
p2 : -7
p2 : -8
p2 : -9
p2 : p1 : -107
p1 : 8
p1 : 9
p1 : 10
Aucun commentaire:
Enregistrer un commentaire