// *** 在 6.0 版本中 ***
import Synchronization
//Mutex 持有它所保护的值
let total = Mutex<Int>(0)
//Atomic 无需锁即可修改值
let hits = Atomic<Int>(0)
await withTaskGroup(of: Void.self) { group in
for i in 1...100 {
group.addTask {
total.withLock { $0 += i }
hits.wrappingAdd(1,
ordering: .relaxed)
}
}
}
let sum = total.withLock { $0 }
//sum is 5050
let count = hits.load(ordering: .relaxed)
//count is 100
print("sum is \(sum)")
print("count is \(count)")