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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started