Last active
June 23, 2023 10:07
-
-
Save NikolaiRuhe/0011e082bfd763715d6ec2c1489c2ec0 to your computer and use it in GitHub Desktop.
This file contains 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 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