Question: This skeleton of a program is designed so that multiple threads will be busy waiting for the next_action variable to be set. Ideally one thread

This skeleton of a program is designed so that multiple threads will be busy waiting for the next_action variable to be set. Ideally one thread would call perform_action whenever the main sets it to a nonzero. Show how mutexes and condition variables can be used to to guarantee this behavior.

// choose a time-consuming activity based on action ...

void perform_action(int action);

int next_action=0;

void* threadfunc(void*)

{

while (1)

{

while (next_action == 0);

int my_action=next_action;

next_action=0;

perform_action(my_action);

}

}

int main()

{

// assume we've spawned threads executing threadfunc ...

while (1)

{

// determine what action should be dispatched to a thread next

next_action=read_action_from_user();

// exit the program

if (next_action == -1) { break; }

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 Databases Questions!