Semaphores Flashcards

1
Q

Example: Vaccination by Locking

A

Lock allows only one in at a time: underutilization of booths

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Example: Vaccination by Semaphore

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Vaccination in Code

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Selling tickets via Semaphore

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What happens if
* Number of buyers and initial number of tickets are equal?
* There are zero tickets initially?
* Number of tickets is greater than the number of buyers?

A

Locks only provide mutual exclusion
– One thread executes in the critical section at a time

May want more threads using resources concurrently
* Produce/consumer problem
– Need one thread to run after the other
– Don’t wish to operate in lockstep

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Semaphore Definition (Dijkstra, 1965)

A

A synchronization primitive implemented via a counter with a nonnegative initial value, and supports two operations that are guaranteed to be atomic:

  • acquire:
    If counter is positive, then decrement counter by 1 and let calling thread continue. If counter is 0, block the thread on the semaphore.
  • release:
    Increment counter by 1. If there are blocked threads on
    the semaphore, unblock some such thread.

acquire aka wait aka P aka down
release aka signal aka V or up
Note: Counter value is never negative!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Semaphore Psuedocode for Mutual Exclusion

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How does this work?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Blocking/Unblocking Management

A

Internally managed by thread system

The thread system records the threads that are blocked on a semaphore. E.g., it may place them in a queue for the semaphore.

When semaphore is incremented, the system picks a thread from the queue to run.

The thread runs whenever it is scheduled!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Implementing Semaphores in Java

A

Each Java object O has an associated monitor M, with two conceptual components, a lock L and wait set W
- L ensures at most one thread in any code synchronized on O
- Recall: synchronized method() {body} in O
equiv. to. method(){synchronized(O){body}}

  • W: maintains threads blocked on M.
    • O.wait() suspends calling thread and adds it to W
      • Can only be called from synchronized blocks
      • Releases L
    • O.notify() takes a thread from W and makes it runnable.
      • Can only be called from synchronized blocks
      • Thread must obtain L before resuming
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Semaphores in Java (Buggy)

A

Semaphores in Java (Fixed)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly