Question: Question 4 . [ Points 7 ] Write a program in C + + for two threads to share a single resource ( e .

Question 4.[Points 7] Write a program in C++ for two threads to share a single resource (e.g., a
license). Use Petersons solution to implement it. Each thread independently requests for
the resource, but only one thread at a time can get it. Once a thread gets the resource, it
keeps it for a random time, and releases it. Then, if another thread is waiting on it, it will
flag[i]= true;
turn = i;
while (flag[j] && turn == j);
lock = TRUE;
flag[i]= FALSE;
get it. Here, the variables turn, flag1 and flag2 are shared variables. Variable turn is set by
either thread. Variable flag1 is set by thread 1 and flag2 by thread2. Let each thread
request and release the resource 3 times, each time holding it for a random time and
releasing it. Write the program in any language of your choice provided it allows you to
create threads. Output should look something like this.
Time: 3:01:021.50 Thread 1 requested the resource
Time: 3:01:021.54 Thread 1 received the resource
Time: 3:01:025.01 Thread 2 requested the resource
Time: 3:01:032.26 Thread 1 released the resource
Time: 3:01:032.28 Thread 2 received the resource
Time: 3:01:040.12 Thread 1 requested the resource
Time: 3:01:040.36 Thread 2 released the resource
Time: 3:01:040.38 Thread 1 received the resource
Time: 3:01:041.11 Thread 2 requested the resource
Time: 3:01:045.16 Thread 1 released the resource
Time: 3:01:045.18 Thread 2 received the resource
Time: 3:01:045.28 Thread 1 requested the resource
Time: 3:01:047.26 Thread 2 released the resource
Time: 3:01:047.38 Thread 1 received the resource
Time: 3:01:048.01 Thread 2 requested the resource
Time: 3:01:048.26 Thread 1 released the resource
Time: 3:01:048.28 Thread 2 received the resource
Time: 3:01:049.36 Thread 2 released the resource

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!