[swift-users] Is this really a race condition?
Guillaume Lessard
glessard at tffenterprises.com
Wed Mar 1 17:29:53 CST 2017
> On Mar 1, 2017, at 3:21 PM, Edward Connell via swift-users <swift-users at swift.org> wrote:
>
> The thread sanitizer on Linux is reporting that I have race conditions in libswiftcore. I eliminated enough code down to this trivial example. Is there really a race condition here or are these bogus errors?
>
> let count = 1000
> var items = [[UInt8]?](repeating: nil, count: count)
>
> DispatchQueue.concurrentPerform(iterations: count) {
> items[$0] = [UInt8](repeating: 7, count: 10)
> }
>
> My real scenario is retrieving data asynchronously, so I just threw in a buffer assignment.
The assignments to array elements are where the race lies.
I don’t know about the libswiftcore part, but: assigning to a shared Array concurrently from multiple threads won't work, because of Array's copy-on-write behaviour. You could do
let items = UnsafeMutablePointer<[UInt8]?>.allocate(capacity: 1)
items.initialize(to: nil, count: count)
DispatchQueue.concurrentPerform(iterations: count) {
items[$0].initialize([UInt8](repeating: 7, count: 10))
}
// you’ll be able to see here that they’re all initialized
items.deallocate(capacity: count)
Cheers,
Guillaume Lessard
More information about the swift-users
mailing list