SwiftSafe:并发情况下的数据存取(线程保护)工具库,Thread synchronization made easy.


SwiftSafe:并发情况下的数据存取(线程保护)工具库 - 敏捷大拇指 - SwiftSafe:并发情况下的数据存取(线程保护)工具库


Performance-sensitive classes need internal state synchronization, so that external accessors don't break the internal invariants and cause race conditions. Using GCD (Grand Central Dispatch) directly can confuse newcomers, because the API doesn't necessarily reflect the actual reason why it's being used. That's why wrapping it in a straighforward Swifty API can introduce a bit more clarity to your code. See examples below.

2、Concurrency modes supported

  • EREW - Exclusive Read, Exclusive Write: The most common synchronization method, where only one thread can read or write your protected resource at one time. One big disadvantage is that it's prone to deadlocks.
  • CREW - Concurrent Read, Exclusive Write: Less common, but IMO more powerful method, where multiple threads can read, but only one thread can write at one time. Reading and writing is automatically made exclusive, i.e. all reads enqueued before a write are executed first, then the single write is executed, then more reads can be executed (those enqueued after the write).


  • iOS 8.0+
  • Swift 3.0+



[Bash shell] 纯文本查看 复制代码
github "nodes-ios/SwiftSafe" ~> 2.0

For Swift 2.2 release:

[Bash shell] 纯文本查看 复制代码
github "nodes-ios/SwiftSafe" ~> 1.0


[Bash shell] 纯文本查看 复制代码
pod 'SwiftSafe'


Let's say you're writing a thread-safe NSData cache. You'd like it to use CREW access to maximize performance.

[Swift] 纯文本查看 复制代码
class MyCache {
    private let storage: NSMutableDictionary = NSMutableDictionary()
    public func hit(key: String) -> NSData? {
        let found = self.storage[key]
        if let found = found {
            print("Hit for key \(key) -> \(found)")
        } else {
            print("Miss for key \(key)")
        return found
    public func update(key: String, value: NSData) {
        print("Updating \(key) -> \(value)")
        self.storage[key] = value

This is the first implementation. It works, but when you start calling it from multiple threads at the same time, yo