lect21

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

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

CMSC 216 Introduction to Computer Systems Lecture 21 Concurrency Jan Plane & Pete Keleher {jplane, keleher}@cs.umd.edu 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

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

View Full Document
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
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];

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### 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
Ask a homework question - tutors are online