Created
June 5, 2025 17:25
-
-
Save mbrandonw/bd57dc852579c32a3f5b20105e85fd8f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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