Wednesday, 8 January 2020

Swift - Is setting variable property concurrency or multithreading safe?

As I know setting variable property concurrency or multithreading is not safe but I can't make it crash with below code.

class Node {
    var data = 0
}

var node = Node()
let concurrentQueue = DispatchQueue(label: "queue", attributes: .concurrent)

for i in 0...1000 {
    concurrentQueue.async {
        node.data = i    // Should get crash at this line
    }
}

UPDATE1

Thanks @MartinR for pointing out in his comment.

Enable the “Thread Sanitizer” and it'll report an error immediately.

UPDATE2

The code got EXC_BAD_ACCESS KERN_INVALID_ADDRESS crash if changing data to reference type. It doesn't always happen but sometimes it will. For example:

class Data {}

class Node {
    var data = Data()
}

var node = Node()
let concurrentQueue = DispatchQueue(label: "queue", attributes: .concurrent)

for i in 0...1000 {
    concurrentQueue.async {
        node.data = Data()    // EXC_BAD_ACCESS KERN_INVALID_ADDRESS
    }
}

This behavior also happens with Objective-C. Setting object property concurrency or multithreading causes crash. But with primate type, I can't make it crash.

Questions

  • Does setting value type property concurrency or multithreading cause crash?
  • If it won't cause crash, what is the difference between setting value type property and setting reference type property.

It's perfect if you can also explain why setting reference type property concurrency causes crash.



from Swift - Is setting variable property concurrency or multithreading safe?

No comments:

Post a Comment