ECE344 Fall 2026 (Sec 1) Lec 18 - Semaphores
Overview
Jon Eyolfson distinguishes mutexes, which protect shared data from races, from semaphores, which coordinate the order in which threads proceed. He develops the semaphore wait/post model through ordered-print examples and applies it to a bounded producer-consumer buffer, using one semaphore for filled slots and another for empty slots while retaining mutexes to protect shared indices.
Key takeaways
- A mutex protects a critical section from concurrent access, but it does not guarantee which thread reaches that section first.
- For a one-way ordering constraint, initialize a semaphore to 0, wait before the action that must be delayed, and post after the prerequisite action.
- A semaphore initialized to 1 can resemble a mutex, but its lack of ownership and dependence on a correctly chosen initial value make a real mutex the safer mutual-exclusion tool.
- A bounded buffer of capacity N needs `filled_slots` initialized to 0 and `empty_slots` initialized to N, with waits before consuming or producing and posts after each slot-state change.
- Semaphores do not eliminate data races: mutexes are still needed to protect shared producer and consumer indices.
Chapters
- At about 8:31, Jon Eyolfson reviews a data race as concurrent accesses to the same memory location where at least one access is a write.
- A mutex makes its lock-to-unlock region a critical section, preventing simultaneous execution there.
- Locks provide mutual exclusion but do not determine which thread runs first.
- The example creates one thread for `print_first` and another for `print_second`, then joins both before `main` exits.
- Thread creation order does not ensure that “This is first” prints before “I'm going second.”
- The required behavior is an ordering constraint, not simply a need to protect shared data.
- A shared flag can make the second thread spin until the first thread changes its value after printing.
- The flag version has a data race because one thread writes the flag while another reads it.
- Adding a mutex around repeated flag checks avoids the race but adds repeated lock and unlock operations.
- Treating a mutex like a binary signal can fail if the first-print thread runs first and leaves the second thread blocked.
- Unlocking an already-unlocked mutex or unlocking a mutex owned by another thread is undefined behavior.
- Separate output calls can interleave; use one mutex around the group of writes when whole-line output is required.
- The POSIX man-page attribute `MT-Safe` indicates a function is safe for concurrent calls from multiple threads.
- `printf` is thread-safe, but multiple calls making up one line can still interleave with calls from another thread.
- Joining the first thread before creating the second enforces order by eliminating the concurrency that the example is meant to preserve.
- A semaphore is a nonnegative integer shared among threads, with atomic `wait` decrement and `post` increment operations.
- `wait` blocks at zero until a `post` makes the value positive, then decrements it; `trywait` attempts the decrement without blocking.
- The POSIX API uses `<semaphore.h>`, `sem_t`, and `sem_init`; `pshared` is set to 0 for the thread-only examples, and the initial value is chosen by the programmer.
- For “This is first” followed by “I'm going second,” place `sem_wait` before the second message and initialize the semaphore to 0.
- Post immediately after the first message; the second thread cannot pass its wait until that post occurs.
- The semaphore guarantees the required ordering while allowing other work in both threads to remain concurrent.
- To order three messages, use a second zero-initialized semaphore: the second thread posts after its message, and the third thread waits on it.
- A semaphore initialized to 1 can imitate a mutex for single-thread-at-a-time access, with `wait` acting like lock and `post` like unlock.
- Semaphores have no owner, so a different thread may post; use semaphores for ordering and mutexes for mutual exclusion.
- The bounded-buffer example uses four circular slots, two producer threads, two consumer threads, and six items per thread.
- Without ordering, consumers can read empty slots, and producers can overwrite data that consumers have not processed.
- Address the earliest failure first: a zero-initialized filled-slot semaphore makes consumers wait until a producer fills a slot and posts.
- Initialize `filled_slots` to 0, wait before each consumer reads, and post after a producer fills a slot.
- Initialize `empty_slots` to the buffer capacity of 4, wait before a producer writes, and post after a consumer empties a slot.
- The two counters keep producers from exceeding available capacity and consumers from consuming unavailable data, while allowing production and consumption to overlap.
- Producer and consumer indices are shared data, so mutexes still protect their increments and circular-buffer wraparound.
- Starting both producer-consumer semaphores at 0 would deadlock: both sides could wait before either side posts.
- The final distinction is that mutexes prevent data races, while semaphores coordinate ordering and resource availability.
Transcript excerpt
1:59 Mhm. >> Mhm.
7:44 >> Mhm. >> Alrighty, welcome back to operating
8:33 system. So, fun day of semaphores. Yay! So, as a recap, so locks gave us mutual exclusion. Have we all remembered what data races are from the top of our head? Two concurrent accesses to the same memory location variable with at least one being a right. If you want to prevent data races, you can use a mutex because anything between the lock and unlock call is a critical section we call where only one thread can be executing that code at a time. Therefore, if only one thread can be executing that code at a time, don't have concurrent accesses, don't have data races. Joy. So, we even built one in lecture 17 with compare and swap or the stupid comp exchange func- or
9:23 assembly instruction. Same thing. And then we solved the bounded wait or the busy wait problem by sticking on a wait queue for them. So, a lock, however, it say which thread gets there first. Like how would we make one thread always run before another? So, this is mostly fun coding examples today. So, let's take this code. So, main thread, I create two threads. I create them. One where is destined to run this print second function. The other is destined to run print first. So, I create them. Both of them. Then, the main thread joins them so that they're all cleaned up.
10:10 And everything and terminated before the main thread return zero, which is the same as exit, which exits the process. And then, print first prints off this is first. Print second prints off I'm going second. As written, if I run this program, what's going to happen? Yeah. >> One of them will print before the other.
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Jon Eyolfson.