QUESTION 3 (20 Marks)
Write a pthreads program that uses mutexes and condition variables to solve a simple synchronization problem involving two children playing a toy. The problem is described as follows.
Two children child_0 and child_1 take turns to play with a toy in rotation. Each child plays with the toy for a specified amount of time. Afterwards, they must pass the toy to the other child.
Initially, child_0 plays with the toy. The children then take turns to play with the toy in the following order until “their parent” has called (i.e., the main thread cancels the child threads): child_0 g _child_1 g _child_0 g _child_1 g _child_0 …
You only need to write a thread routine child_routine(). In the routine children take turns to play in an infinite loop. (There is no problem as the child threads will be terminated by the main thread.)
Your child_routine() needs to insert the following print statements:
When a child is to play, print
printf("child %d: I get to play with the toy for %d units of time.\n", myid->id, play_time);
When a child is to stop playing and pass the toy to the other child, print
printf("child %d: I now give the toy to the other child.\n", myid->id);
In the above play_time is a fixed number of seconds. When a child is playing, just use sleep(play_time) function to put it into sleep for play_time seconds.