Question: This problem is about critical sections. ( Note: If any part of your answer comes from an AI system, you must cite the system you
This problem is about critical sections. Note: If any part of your answer comes
from an AI system, you must cite the system you use and tell what prompts you gave. Consider
an implementation of a LIFO list, implemented by the following code:
typedef struct element
void value;
struct element next;
elemt;
void insertelemt l void val
elemt e mallocsizeofelemt; asserte;
evalue val;
enext l;
l e;
void getelemt l
void rv NULL;
elemt e l;
if e
l enext;
rv evalue;
freee;
return rv;
A certain program will use threads that share an instance of the above implementation and update
it via the insert and get functions. Note that an instance can be created simply by declaring a
variable of type elemt and initializing it to NULL.
a Identify any critical sections in the two functions above, by giving the range of line numbers
that could give incorrect results if interleaved in the execution of two threads.
b What statements need to be added to the insert and get functions to implement mutual
exclusion using a pthreads mutex?
c What additional function will need to be implemented in order for the modified code to work?
d The code, as written, returns NULL if the list is empty. This is not very useful if the list is used
to say, store pointers to jobs, because a thread must waste cycles repeatedly calling get to
obtain useful work to do A more useful semantic is for the thread calling get to block if
the list is empty, and for a thread that calls insert on an empty list to awaken a thread
blocked in get. Rewrite the synchronized get and insert functions to implement this
blocking semantics; also add any additional code needed to make it work correctly. It is OK
for threads calling get to block forever if nothing is ever inserted.
Note: this is a subtle problem. You will need to use a condition variable pthreadcondt
to implement this correctly. See the man page for pthreadcondwait and the slides from
lecture that show how to use condition variables. The man pages are long, but the first
halfdozen paragraphs of pthreadcondwait tell you most of what you need to know. The
paragraph Condition Wait Semantics is also important. You will need to initialize the
condition variable.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
