Skip to content

Commit 62ea95a

Browse files
committed
Documentation
1 parent 6ab8b55 commit 62ea95a

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ Unlike [`DispatchSemaphore`], `Semaphore` does not block any thread. Instead, it
66

77
### Usage
88

9+
You can use a semaphore to suspend a task and resume it later:
10+
911
```swift
1012
let semaphore = Semaphore(value: 0)
1113

@@ -19,6 +21,23 @@ Task {
1921
semaphore.signal()
2022
```
2123

24+
You can use a semaphore in order to make sure an actor's methods can't run concurrently:
25+
26+
```swift
27+
actor MyActor {
28+
private let semaphore = Semaphore(value: 1)
29+
30+
func serializedMethod() async {
31+
// Makes sure no two tasks can execute self.serializedMethod() concurrently.
32+
await semaphore.wait()
33+
defer { semaphore.signal() }
34+
35+
await doSomething()
36+
await doSomethingElse()
37+
}
38+
}
39+
```
40+
2241
The `wait()` method has a `waitUnlessCancelled()` variant that throws `CancellationError` if the task is cancelled before a signal occurs.
2342

2443
For a nice introduction to semaphores, see [The Beauty of Semaphores in Swift 🚦](https://medium.com/@roykronenfeld/semaphores-in-swift-e296ea80f860). The article discusses [`DispatchSemaphore`], but it can easily be ported to Swift concurrency: see the [demo playground](Demo/SemaphorePlayground.playground/Contents.swift) of this package.

0 commit comments

Comments
 (0)