Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you need is 2 threads (parent and child) allowing each other to execute. </p> <p>This is the pseudo-code, you are free to use any locking primitives you want.</p> <pre><code>//global variables and initializations parent_lock = UNLOCKED; //This allows your first print to be from parent child_lock = LOCKED; parent_counter = 0; //to count the number of prints child_counter = 0; //Parent should do this | //Child should do this while(1) |while(1) { | spin: if(parent_lock == LOCKED) |spin: if(child_lock == LOCKED) { | { //spin till child unlocks you | //spin till parent unlocks you goto spin; | goto spin; } | } else | else { | { print("PARENT"); | print("CHILD"); parent_counter++; | child_counter++; //lock yourself allow the other| //lock yourself allow the other parent_lock = LOCKED; | child_lock = LOCKED; child_lock = UNLOCKED; | parent_lock = UNLOCKED; if (parent_counter == 10) | if (child_counter == 10) { | { break;//printed 10 times | break; } | } } | } } |} //PARENT has printed 10times wait for |//CHILD has printed 10times wait for //child |// parent </code></pre> <p><strong>PS</strong>: *I assume you are free to spin on a lock which is what I have done, if that's not the case you need to modify the above algorithm to do sleep and wake up instead of spin.<br> *You can choose pthread lock primitives to initialize the parent_lock and child_lock.<br> *For the program to be correct we need to assume that assignment statements are atomic Ex: child_lock = LOCKED statement is atomic.</p> <p><strong>Extremely Important</strong>: See the order in parent:</p> <pre><code>parent_lock = LOCKED; child_lock = UNLOCKED; </code></pre> <p>and its counter part in the child thread. If you interchange this two lines then you may DEADLOCK!!!!, because of a sequence of mixed execution by parent and child(due to OS scheduler).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload