Hi,
I am hoping to pick the collective brains of developers interested in Swift and concurrency. Forgive me if this is on the forum somewhere, I did search and couldn't find anything.
I have been having problems using grand central dispatch (GCD) and wrote this test (which is a considerable cut down of what I am trying to do):
import Foundation
let numThreads = 16
let threadIndexes = 0 ..< numThreads
let numTests = 8
(0 ..< numTests).forEach { (testIndex) in
var arrays = [Int?](count: numThreads, repeatedValue: nil)
let groups = threadIndexes.map { (_) in
dispatch_group_create()
}
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
threadIndexes.forEach { (threadIndex) in
dispatch_group_async(groups[threadIndex], queue) {
arrays[threadIndex] = threadIndex
}
}
threadIndexes.forEach { (threadIndex) in
dispatch_group_wait(groups[threadIndex], DISPATCH_TIME_FOREVER)
if arrays[threadIndex] == nil {
print("test \(testIndex), array element \(threadIndex) = nil")
}
}
}
I think what I am trying to do should work because I do wait for the treads to finish. However I find the test fails on most runs, typical output is:
test 3, array element 14 = nil
test 3, array element 15 = nil
test 4, array element 5 = nil
test 5, array element 14 = nil
test 6, array element 12 = nil
I am using Xcode 7b6 on a MacBook Pro (15-inch, Early 2011) with a 2.3 GHz Intel Core i7 running 10.10.4 (14E46).
Is this a memory consistency problem?
Is their a memory model for Swift? Is the model like C++11, Java, etc.?
Is there some code that can be added to the above to make the test work (I have stried a loop waiting for non null and whilst this is better sometimes it just continually loops)?
Thanks in advance for any advice,
-- Howard.