Skip to content

Instantly share code, notes, and snippets.

@mbrandonw
Created June 5, 2025 17:25
Show Gist options
  • Save mbrandonw/bd57dc852579c32a3f5b20105e85fd8f to your computer and use it in GitHub Desktop.
Save mbrandonw/bd57dc852579c32a3f5b20105e85fd8f to your computer and use it in GitHub Desktop.
import Synchronization
import SwiftUI
final class Counter1: Sendable {
let count = Mutex(0)
func increment() {
count.withLock { $0 += 1 }
}
func increment10000() {
for _ in 1...10_000 {
increment()
}
}
}
final actor Counter2 {
var count = 0
func increment() {
count += 1
}
func increment10000() {
for _ in 1...10_000 {
increment()
}
}
}
struct ContentView: View {
var body: some View {
Form {
Button("Mutex") {
let start = Date()
defer { print("mutex", Date().timeIntervalSince(start).formatted()) }
let counter = Counter1()
counter.increment10000()
}
Button("Actor") {
Task {
let start = Date()
defer { print("actor", Date().timeIntervalSince(start).formatted()) }
let counter = Counter2()
await counter.increment10000()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment