0
let queue1 = DispatchQueue(label: "queue1")
let queue2 = DispatchQueue(label: "queue2")

var list: [Int] = []
public func changeList() {
    queue1.async {
        while true {
            if self.list.count < 10 {
                self.list.append(self.list.count)
            } else {
                self.list.removeAll()
            }
        }
    }

    queue2.async {
        while true {
            // case 1
            // self.list.forEach { debugPrint($0) }

            // case 2
            let value = self.list
            value.forEach { debugPrint($0) }

            // case 3
            // var value = self.list
            //value.append(100)
        }
    } 
}

I create two queue to handle an array in different thread. In one thread I write the array and in another thread I read the array. But why does it crash in case 1、case 2 and case 3. Does it mean struct is not thread safe. I have made let value = self.list in case 2.But it also crash, why???

dowZhang
  • 470
  • 1
  • 3
  • 18
  • Why do you expect that? You are fully responsible to synchronize read/write access to your data to make it thread-safe. You could use some barrier synchronization or even other approaches to do it. – user3441734 Dec 03 '18 at 12:27
  • [Create thread safe array in swift](https://stackoverflow.com/questions/28191079/create-thread-safe-array-in-swift/28976644#28976644) – dowZhang Dec 03 '18 at 14:52
  • I have made `let value = self.list` in case 2.But it also crash, why?@Martin R – dowZhang Dec 03 '18 at 14:56

0 Answers0