






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







CS107 Handout 26 Spring 2008 May 9, 2008
Written by Julie Zelenski Semaphore Patterns
One of the latest developments in software engineering is to identify patterns repeated within programs that can be isolated from their context and applied in alternate situations (ideas such as linear search or divide-and-conquer) as a means of cataloguing problem-solving techniques and managing program complexity. It's a pretty handy idea so we at CS107 thought it might be helpful to describe the common semaphore patterns. Hopefully, these descriptions can help you sort out some of the different ways semaphores are used and give you some insight into what options you have for solving different concurrent problems.
Binary lock : The semaphore is used as a single-owner lock. It is initialized to a value of 1 and threads will bracket critical regions with a matched wait and signal on this semaphore. A binary lock semaphore should only ever takes on the value 0 (locked) and 1 (available). This sort of semaphore pattern is used to serialize access to some shared state or resource that only one thread can be using at a time.
Generalized counter : The semaphore is used to count some resource, be it empty buffers, full buffers, clean dishes, or whatever. The semaphore is basically just used as an integer counter, capitalizing on its atomic increment and decrement and the efficient blocking when at zero. The semaphore is initialized to the starting amount of the resource (sometimes 0, sometimes N, it depends). As threads require a resource, they wait on the semaphore to consume one. Other threads (possibly but not necessarily the same threads that consume) signal the semaphore when a new resource available. This sort of semaphore pattern is used to efficiently coordinate shared use of a limited resource that has a discrete quantity. It can also be used to limit throughput (such as in the Dining Philosophers) where uncontrolled contention can lead to deadlock.
Binary rendezvous : The semaphore is used to coordinate on some action taking place. Let's say Thread A needs to know that Thread B has finished some task before it can make progress. Rather than having A repeatedly loop and check some global state, a binary rendezvous can be set up between the two. The rendezvous semaphore is initialized to the value 0. When Thread A gets to the point that it needs to know that the task is done, it will wait on the rendezvous semaphore. After completing the necessary task, B will signal it. If A gets to the rendezvous point before B finishes the task, it will efficiently block until B's signal. If B finishes the task first, it signals the semaphore, recording that the task is done, and when A gets to the wait, it will be able to sail right through. A binary rendezvous semaphore records the status of one event and only ever takes on the value 0 (not-yet-completed or completed-and-checked) and 1 (completed- but-not-yet-checked). The binary rendezvous pattern is often used to wakeup another
thread (such as disk reading thread that should spring into action when a request comes in) or to coordinate two dependent actions (a print job request that can't complete until it the paper is refilled) and so on. If you need a two-way rendezvous where both threads need to wait for the other, you can add another semaphore in the reverse direction, with the wait and signal calls inverted. Be careful that both threads donโt try to wait for the other first and signal afterwards (remember the water example from lecture), else you can quickly land in deadlock!
Generalized rendezvous : A combination of the ideas in the binary rendezvous and the generalized counter. This semaphore is used to record how many times some action has taken place. For example, if Thread A spawned 5 Thread Bs and needs to wait for all of them to finish before going on, a generalized rendezvous can be used. The generalized rendezvous is initialized to the value 0. When Thread A needs to synch up with the others, it will call wait on the semaphore in a loop, one time for each thread it is synching up with. Thread A doesn't care which specific thread of the group has finished, just that another has. If Thread A gets to the rendezvous point before the threads have finished, it will efficiently block, waking to "count" each as it signals, and will only move on when all have checked back in. If all the B threads have finished before A arrives at the rendezvous point, it will be able to quickly decrement the semaphore once for each thread and move on. The current value of the generalized rendezvous semaphore gives you a count of the number of tasks that have completed that haven't yet been checked, it will be somewhere between 0 and N at all times. The generalized rendezvous pattern is most often used to regroup after a divided task such as waiting for several network requests to complete or blocking until all pages in a print job have been printed.
Layered construction : Once you have the basic patterns down, you can start to think about how semaphores can be layered into more complex constructions. For example, consider the constrained dining philosopher solution in which a generalized counter is used to constrict the throughput and once inside, binary locks are used for each of the forks. Another layered construct might be a global integer counter with a lock and a binary rendezvous that can do something similar to that of a generalized semaphore. As tasks complete, they could lock and decrement the global counter, and when the counter got to 0, a single signal to the rendezvous could be sent out by the thread that was the last to finish. The combination of a lock with a binary rendezvous could be used to set up a "race": Thread C is waiting for one of Thread A or B to signal. Thread A and B each try to be one who signals the rendezvous. Thread C only expects exactly one signal, thus the lock is used to serialize access so that only the first thread signals, not both. And there are many others you could construct.
/**
#include <stdio.h> #include "thread_107.h"
#define NUM_CUSTOMERS 10 #define SECOND 1000000
static void Cashier(void); static void Clerk(Semaphore done); static void Manager(int totalNeeded); static void Customer(int numToBuy); static void SetupSemaphores(void); static void FreeSemaphores(void); static int RandomInteger(int low, int high); static void MakeCone(void); static bool InspectCone(void); static void Checkout(int linePosition); static void Browse(void);
/* We have many variables accessed by multiple threads in this program and
struct inspection { // struct of globals for Clerk->Manager rendezvous Semaphore available; // lock used to serialize access to the one Manager Semaphore requested; // signaled by clerk when cone is ready to inspect Semaphore finished; // signaled by manager after cone has been inspected bool passed; // status of the last inspection } inspection;
struct line { // struct of globals for Customer->Cashier line Semaphore lock; // lock used to serialize access to counter int nextPlaceInLine; // counter Semaphore customers[NUM_CUSTOMERS]; // rendezvous for customer by position Semaphore customerReady;// signaled by customer when ready to check out } line;
/*
int main(int argc, char **argv) { int i, numCones, totalCones = 0; bool verbose = (argc == 2 && (strcmp(argv[1], "-v") == 0)); InitThreadPackage(verbose); SetupSemaphores(); for (i = 0; i < NUM_CUSTOMERS; i++) { char name[32]; sprintf(name, "Customer %d", i); numCones = RandomInteger(1, 4); // each customer wants 1 to 4 cones ThreadNew(name, Customer, 1, numCones); totalCones += numCones; } ThreadNew("Cashier", Cashier, 0); ThreadNew("Manager", Manager, 1, totalCones); RunAllThreads(); printf("All done!\n"); FreeSemaphores(); return 0; }
/**
static void Manager(int totalNeeded) { int numPerfect = 0, numInspections = 0; while (numPerfect < totalNeeded) { SemaphoreWait(inspection.requested); inspection.passed = InspectCone(); // safe since clerk acquired lock numInspections++; if (inspection.passed) numPerfect++; SemaphoreSignal(inspection.finished); } printf("Inspection success rate %d%%\n", (100*numPerfect)/numInspections); }
SemaphoreSignal(line.lock); SemaphoreSignal(line.customerReady); // signal to cashier we are in line SemaphoreWait(line.customers[myPlace]); // wait til checked through printf("%s done!\n", ThreadName()); }
/*
static void Cashier(void) { int i; for (i = 0; i < NUM_CUSTOMERS; i++) { SemaphoreWait(line.customerReady); Checkout(i); SemaphoreSignal(line.customers[i]); } }
/*
static void SetupSemaphores(void) { int i; inspection.requested = SemaphoreNew("Inspection Requested", 0); inspection.finished = SemaphoreNew("Inspection Finished", 0); inspection.available = SemaphoreNew("Manager Available", 1); inspection.passed = false; line.customerReady = SemaphoreNew("Customer ready", 0); line.lock = SemaphoreNew("Line lock", 1); line.nextPlaceInLine = 0; for (i = 0; i < NUM_CUSTOMERS; i++) line.customers[i] = SemaphoreNew("Customer in line", 0); }
static void FreeSemaphores(void) { int i; SemaphoreFree(inspection.requested); SemaphoreFree(inspection.finished); SemaphoreFree(inspection.available); SemaphoreFree(line.customerReady); SemaphoreFree(line.lock); for (i = 0; i < NUM_CUSTOMERS; i++) SemaphoreFree(line.customers[i]); }
/* These are just fake functions to stand in for processing steps */
static void MakeCone(void) { ThreadSleep(RandomInteger(0, 3*SECOND)); // sleep random amount printf("\t%s making an ice cream cone.\n", ThreadName()); }
static bool InspectCone(void) { bool passed = (RandomInteger(1, 2) == 1); printf("\t\t%s examining cone, did it pass? %c\n", ThreadName(), (passed? 'Y':'N')); ThreadSleep(RandomInteger(0, .5*SECOND)); // sleep random amount return passed; }
static void Checkout(int linePosition) { printf("\t\t\t%s checking out customer in line at position #%d.\n", ThreadName(), linePosition); ThreadSleep(RandomInteger(0, SECOND)); // sleep random amount }
static void Browse(void) { ThreadSleep(RandomInteger(0, 5*SECOND)); // sleep random amount printf("%s browsing.\n", ThreadName()); }
/*
static int RandomInteger(int low, int high) { extern long random(); long choice; int range = high - low + 1; PROTECT(choice = random()); // protect non-re-entrant random return low + choice % range; }
Manager examining cone, did it pass? Y Cashier checking out customer in line at position #3. Customer 0 done! Inspection success rate 61% Customer 3 done! All done!
Points to Ponder
You can take this starting simulation and extend it with more features and participants to demonstrate even more sophisticated concurrency controls. Here are a few extensions you might want to think through to give yourself practice design more complex coordination: