Created
May 14, 2025 17:43
-
-
Save tapoton/f3507c4199ff1c6aaa8d846e3cc0749a to your computer and use it in GitHub Desktop.
Data race demo
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 Foundation | |
| import Synchronization | |
| final class Counter: Sendable { | |
| private let mutex = Mutex(0) | |
| var count: Int { | |
| get { | |
| return mutex.withLock { count in | |
| return count | |
| } | |
| } | |
| } | |
| func setCount(_ newCount: Int) { | |
| mutex.withLock { count in | |
| count = newCount | |
| } | |
| } | |
| func increment() { | |
| setCount(count + 1) | |
| } | |
| } | |
| let counter = Counter() | |
| await withTaskGroup { group in | |
| for _ in 0..<1000 { | |
| group.addTask { | |
| counter.increment() | |
| } | |
| } | |
| await group.waitForAll() | |
| } | |
| print(counter.count) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's safe like this: