Download presentation
Presentation is loading. Please wait.
1
Problem: CFQ (Circular Fifo Queue)
#define N // the queue size shared memory int CFQ[N]; // the CFQ shared memory int nTop; // pointer to the top of the queue shared memory int nTail; // pointer to the tail of the queue void producer (void) { int new_item; // a place holder for a new item while (TRUE) new_item = produce_item( ); // produce a new item while (empty < 1) // wait until a space in the CFQ { ; } // as a “spin wait” CFQ[nTail] = new_item; // insert the new item to the CFQ nTail = (nTail + 1) % N; // update the tail pointer empty = empty – 1; // empty slots is decreased by one } void consumer (void) { int new_item; // a place holder for a new item while (TRUE) while (empty > 1) // wait until at least one item in the CFQ { ; } // as a “spin wait” new_item = CFQ[nTop]; // remove the first item in the CFQ nTop = (nTop + 1) % N; // update the top pointer empty = empty + 1; // empty slots is decreased by one do_something (new_item); } What are the problems (two major problems)?
2
FIRST SOLUTION Producer Process Consumer Process
#define N // Queue Size #define NUM_REPEAT 1,000, // Number of items to be generated semaphore MUTEX // binary semaphore SM: a pointer to the queue in shared memory SMnum_element = 0; // # of the random # produced to the queue Producer Process Consumer Process int i; // loop counter int new_item; // the new random # int tail = 0; // the position for the new # for (i=0; i < NUM_REPEAT; i++) { new_item = rand( ); if(SMnum_element < N) wait(MUTEX); SM[tail] = new_item; SMnum_element ++; signal(MUTEX); tail ++; if (tail N) tail = 0; } else { i--; } int top = 0; // the position for the new # if(SMnum_element > 0) new_item = SM[top]; SMnum_element --; top ++; if (top N) top = 0; FIRST SOLUTION
3
SECOND SOLUTION Producer Process Consumer Process
#define N // Queue Size #define NUM_REPEAT 1,000, // Number of items to be generated semaphore MUTEX // binary semaphore semaphore EMPTY N // counting semaphore semaphore FULL // counting semaphore SM: a pointer to the queue in shared memory Producer Process Consumer Process int i; // loop counter int new_item; // the new random # int tail = 0; // the position for the new # for (i=0; i < NUM_REPEAT; i++) { wait(EMPTY); new_item = rand( ); wait(MUTEX); SM[tail] = new_item; signal(MUTEX); tail ++; if (tail N) tail = 0; signal(FULL); } int top = 0; // the position for the new # wait(FULL); new_item = SM[top]; top ++; if (top N) top = 0; signal(EMPTY);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.