Operating Systems Critical Section c++ code help require


the algorithm is for two processes

lock variable initially 0
when a process wants to enter its critical region, it first test the lock if lock is 0 the process will set it to 1 and enters the critical region.
if the lock is already 1 the process will wait until it becomes 0 , thus 0 means that no process is in its critical region.

The result is showing just "process 1 waiting" not switching processes. what should i change or add in the code .

code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
    #include<stdio.h>
#include<conio.h>
#include <cstdlib>




int lock=0;
void func1();
void func2();

int main()
{


func1();
func2();
getch();

}
void func1()
     {
            while (lock!=0);
                  {
                          printf("Process1 waiting");
                          getch();
                          exit(0);



                   lock=1;

                          func2();
                          printf("in critical state of Process1");
                          getch();             


                  } 

     }

     void func2()
     {
          while(lock!=0);
               {
                  printf("Process2 waiting");
                  getch();
                  exit(0);



                  lock=1;
                  {
                  printf("In Critical State of Process2");
                  getch();
                  }

              }
     }
func1() and func2() do not run parallel so there is no way that func2() will ever run.

Once lock=1 line 23 is an infinite loop. But this will never happen since line 27 will exit your program.
I tried to change the code , but still the critical section problem is not resolved can you help please



#include<conio.h>

#include <iostream>


using namespace std;

int lock=0;
int func1();
int func2();

int main()
{


func1();
func2();
getch();

}
int func1()
{
while (lock!=0);
{
cout<<"Process 1 waiting";

getch();

return 1;
exit(0);

lock=1;

func2();

cout<<"in critical state of Process1";

getch();
exit(0);

}

}

int func2()
{
while(lock!=0);
{
cout<<"Process2 waiting";

getch();




lock=1;
{
cout<<"In Critical State of Process2";

getch();
}

}
}
You cannot do it like that.

Either you have really two processes (i.e. two independent programs).
Or you simulate it with two threads:

http://www.cplusplus.com/reference/thread/thread/?kw=thread
Topic archived. No new replies allowed.