Skip to content

Instantly share code, notes, and snippets.

@NikolaiRuhe
Last active June 23, 2023 10:07
Show Gist options
  • Save NikolaiRuhe/0011e082bfd763715d6ec2c1489c2ec0 to your computer and use it in GitHub Desktop.
Save NikolaiRuhe/0011e082bfd763715d6ec2c1489c2ec0 to your computer and use it in GitHub Desktop.
import XCTest
final class BarrierTests: XCTestCase {
func test() async {
let subsystem = Subsystem()
await withTaskGroup(of: Void.self) { group in
for index in 0 ..< 100 {
group.addTask { subsystem.performWork(id: index) }
}
await group.waitForAll()
}
}
}
final class Subsystem: Sendable {
let queue = DispatchQueue(label: "my concurrent queue", attributes: .concurrent)
func performWork(id: Int) {
if id % 10 == 0 { write(id: id) }
else { read(id: id) }
}
func write(id: Int) {
print("schedule exclusive write \(id)")
queue.async(flags: .barrier) { print(" execute exclusive write \(id)") }
print("schedule exclusive write \(id) done")
}
func read(id: Int) {
print("schedule read \(id)")
queue.sync { print(" execute read \(id)") }
print("schedule read \(id) done")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment