lect21 - CMSC 216 Introduction to Computer Systems Lecture...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
CMSC 216 Introduction to Computer Systems Lecture 21 Concurrency Jan Plane & Pete Keleher {jplane, [email protected] Semaphores • To properly implement a critical section, we can use semaphores • These are special global variables, with nonnegative integer values, that can only be changed by two operations – in most literature, called P and V – we'll restrict ourselves to discussion of binary semaphores here, but semaphores can be more than just 0/1 values • Used to ensure that only one thread is in a critical section at a time CMSC 216 - Wood, Sussman, Herman, Plane 2
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Semaphores, cont. P (s), or wait operation – if s is 0, waits until s is 1 – if s is 1, sets s to 0 (decrements s) V (s), or post operation – if s is 0, sets s to 1 (increments s), and restarts exactly one of the processes waiting for s to be 1 – should not be called except after a P (s) call • All elements of these operations are indivisible (i.e., these operations are atomic) CMSC 216 - Wood, Sussman, Herman, Plane 3 Using semaphores • Three functions, all in <semaphore.h> • Each return 0 on success, -1 on error int sem_init(sem_t *s, 0, unsigned int value); – initializes the semaphore pointed at by s to value – you must initialize semaphores before use – the second argument will always be 0 for our purposes int sem_wait(sem_t *s); – performs the P (s) operation int sem_post(sem_t *s); – performs the V (s) operation CMSC 216 - Wood, Sussman, Herman, Plane 4
Background image of page 2
Example using semaphores #define LOOPS 10000000 static int count = 0; static sem_t mutex; void *counter(void *args) { int i; for (i = 0; i < LOOPS; i++) { sem_wait(&mutex); count++; sem_post(&mutex); } printf("Executed %d times\n", i); return NULL; } int main() { pthread_t tids[2];
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/13/2012 for the course CMSC 216 taught by Professor Plane during the Spring '11 term at Maryland.

Page1 / 8

lect21 - CMSC 216 Introduction to Computer Systems Lecture...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online