-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
One of the major goals of Swift 6 was to ensure data-race safety. These changes are designed to help concurrent code run predictably and to avoid crashes.
A data race happens when multiple threads simultaneously access the same piece of mutable data at the same time, where at least one of these accesses modifies the data. This can lead to unpredictable behavior and even crashes, since the result depends on the random timing of these concurrent accesses.
Let’s take a look at what a data-race condition is by examining the following code:
var count = 0
let queue = DispatchQueue.global()
func incrementCount() {
for _ in 0..<1000 {
queue.async {
count += 1
print(count)
}
}
}
incrementCount()
print("Final: \(count)")
When this code is run, one of the first thing that would be noticed is the output from within the incrementCount() function would be out of order. The end of the output may look something...