Presentation is loading. Please wait.

Presentation is loading. Please wait.

Synchronization and Scheduling

Similar presentations


Presentation on theme: "Synchronization and Scheduling"— Presentation transcript:

1 Synchronization and Scheduling
Section 6 Synchronization and Scheduling February 24th, 2017 Taught by Joshua Don

2 Locks Synchronization primitive
Provides mutual exclusion to a critical section/shared resource Only one thread may own the lock at a time. Trying to acquire a held lock causes a thread to block. Has a holder -> implies ownership Locking mechanism struct lock lock; lock_init(&lock); lock_acquire(&lock); // critical section lock_release(&lock);

3 Semaphores Synchronization primitive Prevents resource contention
Generalized mutex Signaling mechanism Initialized with a value. Can be ‘downed’ as many times as ‘value’ before a thread must block. Can be ‘upped’ by any thread struct semaphore sema; sema_init(&sema, 1); sema_down(&sema); // restricted mutual access sema_up(&sema);

4 Semaphores Continued Should you ever try to read the current value of a semaphore directly? No; it creates a race condition, the value could change right after you read it

5 When to use: lock vs. sema(1)?

6 Lock vs Sema(1) Thread A Thread B
A lock is a locking mechanism, while a semaphore is a signaling mechanism A semaphore can be ‘upped’ by any thread, whereas a lock can only be released by its holder struct semaphore event; sema_init(&event, 0); Thread A Thread B // wait for event sema_down(&event); handleEvent(); createEvent(); // signal that event has occurred sema_up(&event);

7 Lock vs sema(1) continued
In Pintos:thread.c, this exact signaling behavior is used for the idle thread! Check out the use of struct semaphore idle_started;

8 Monitors NOT a synchronization primitive
Composed of a lock and one more condition variables Condition variables: A list of threads waiting for an event to occur There is no such thing as a ‘struct monitor’ (unless you make one!) Must acquire the lock before checking the condition! A thread acquires the monitor lock Check if some condition is not met, if so call wait(&cond, &mutex) – atomically releases the lock and adds the thread to the condition variable Another thread acquires the monitor lock The thread changes the original condition that the threads on cond are waiting for. Can now either signal cond (wake up one waiter) or broadcast (wake up all)

9 Monitor example struct lock mutex; struct cond_t space_available;
struct cond_t data_available; AddToQueue(item) { lock_acquire(&mutex); while (queue.isFull()) { cond_wait(&space_available, &mutex); } queue.push_back(item); cond_signal(&data_available); lock_release(&mutex); RemoveFromQueue() { lock_acquire(&mutex); while (queue.isEmpty()) { cond_wait(&data_available, &mutex); } queue.pop(); cond_signal(&space_available); lock_release(&mutex);


Download ppt "Synchronization and Scheduling"

Similar presentations


Ads by Google