Ask a question to Desklib · AI bot

Ask NowBETA

Pseudocode- Semaphore Abstract

Added on -2019-09-16

| 5 pages
| 1114 words
| 927 views

Trusted by 2+ million users,
1000+ happy students everyday

1.Please complete the following pseudocode to implement the semaphore abstract. publicclass Semaphore {// A private variable to set the bufferPrivate int value;void init(intval){//initialize value if val>0}publicvoid Wait(){repeatwait();until value is 0decrement the value}void signal(){If value is 0Notify();End ifIncrement value;}}2.Write the Pseudocode for the following problems: ssignalpose there are three threads A,B and C. A keeps producing an item into a buffer B1 of size M, B keeps taking an item from B1, and put into another buffer B2 of size N. C keeps consuming an item from buffer B2. Please write the pseudocode for Thread A,B,C a.Using the semaphores class defined above to synchronize them. b.Using the Monitor abstract to synchronize them.A)Initialize Buffer b1 with buffer size M.semaphore mutex = 1; // Controls access to critical sectionsemaphore empty = M; // counts number of empty buffer slotssemaphore full = 0; // counts number of full buffer slotssemaphore mutex1 = 1;semaphore empty1 = N; semaphore full1 = 0;
Thread A:while (TRUE) { // loop forever make_new(object); // create a new widget to put in buffer wait(&empty); // decrement the empty semaphore wait(&mutex); // enter critical section put_item(object); // put widget in buffer signal(&mutex); // leave critical section signal(&full); // increment the full semaphore }Thread B:while (TRUE) { // loop forever wait(&full); // decrement the full semaphore wait(&mutex); // enter critical section remove_item(object); signal(&mutex); // leave critical section signal(&empty); // increment the empty semaphore wait(&empty1); // decrement the empty semaphore wait(&mutex1); // enter critical section put_item(object); // put widget in buffer signal(&mutex1); // leave critical section signal(&full1); // increment the full semaphore }while (TRUE) { // loop forever make_new(object); // create a new widget to put in buffer }Thread C:while (TRUE) { // loop forever wait(&full1); // decrement the full semaphore wait(&mutex1); // enter critical section remove_item(object); // take a widget from the buffer signal(&mutex1); // leave critical section signal(&empty1); // increment the empty semaphore consume_item(widget); // consume the item }B)monitor ThreeThreadscondition full, empty,full1,empty1;int count,count1;ThreadA enter(); {if (count == M) wait(full); // if buffer is full, block put_item(widget); // put item in buffer count = count + 1; // increment count of full slotsif (count == 1) signal(empty); // if buffer was empty, wake Thread B }

Found this document preview useful?

You are reading a preview
Upload your documents to download
or
Become a Desklib member to get accesss

Students who viewed this