iOS GCD 必读推荐,有关于单例使用问题

链接如下:http://www.cocoachina.com/swift/20150129/11057.html

以前只注意使用dispatch_once达到创建单例对象时的线程安全,读了下边这篇文章,才突然发现以前的做法漏洞百出:仅仅保证创建时的线程安全是完全不够的,要保证单例变量读取时的线程安全!

 

 我感兴趣的部分就是其中关于多线程时的单例成员变量访问部分,swfit语言写的,这里的concurrentPhotoQueue是一个自己建立的并发queue。

func addPhoto(photo: Photo) {
  dispatch_barrier_async(concurrentPhotoQueue) { // 1
    self._photos.append(photo) // 2
    dispatch_async(GlobalMainQueue) { // 3
      self.postContentAddedNotification()
    }
  }
}
var photos: [Photo] {
  var photosCopy: [Photo]!
  dispatch_sync(concurrentPhotoQueue) { // 1
    photosCopy = self._photos // 2
  }
  return photosCopy
}
这个例子很好地说明了
dispatch_sync的使用场景

注意第一个函数中的dispatch_barrier_async是重点!

posted @ 2015-09-05 12:02  幻化成疯  阅读(203)  评论(0编辑  收藏  举报