Semaphore
- Kotlin course
- Advanced
- Lesson 68/83
- 5 min
Learn counted access with Semaphore.
Limiting with Semaphore
Semaphore allows a limited number of coroutines at once. With withPermit { } you acquire a permit; the permit is returned at the end of the block.
Example: val s = Semaphore(3); s.withPermit { fetch() }. At most 3 coroutines can call fetch at a time; others wait. A Mutex can be thought of as a Semaphore(1). This pattern protects external resources from overload.
Permit count and waiting
Semaphore(n) sets n permits. Each withPermit takes one permit; if all are taken, the coroutine waits. When a permit is released, the next one proceeds.
Example: Semaphore(2). If three coroutines call withPermit, two run in parallel, the third waits until one finishes. This pattern keeps parallelism under control; it protects system resources.
Practice A permitted block with Semaphore
Open main with runBlocking. Create val s = Semaphore(2) and add the call s.withPermit { println("permit") }. Include the necessary imports.
Starter code
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
// open main with runBlocking
// create a two-permit Semaphore, print with withPermitSample solution
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
fun main() = runBlocking {
val s = Semaphore(2)
s.withPermit {
println("permit")
}
}Expected output
permit
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the withPermit call
val s = Semaphore(3)
s.____ { fetch() }
val s = Semaphore(3)
s.withPermit { fetch() }
Explanation: withPermit acquires and returns a permit.
2 What is the relationship between Semaphore(1) and Mutex?
Semaphore(1) is like Mutex.- They do different things
- Mutex is Semaphore(0)
- Semaphore(1) behaves like Mutex Correct answer
- They are unrelated
Explanation: Semaphore(1) acts like a single-permit Mutex.
3 Match the Semaphore parts
| Term | Meaning |
|---|---|
Semaphore(3) |
Permit count |
withPermit { } |
Permitted block |
fetch() |
Limited op |
permit release |
Safety |