Code Monkey home page Code Monkey logo

swiftconcurrentcollections's Introduction

SwiftConcurrentCollections

Intro

Swift Concurrent Collections (or SCC) is a library providing concurrent (thread-safe) implementations of some of default Swift collections. Similar to ones found in java.util.concurrent for Java.

Installation

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding SwiftConcurrentCollections as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/peterprokop/SwiftConcurrentCollections.git", .branch("master"))
]

Carthage

In your Xcode project folder do:

  • echo "github \"peterprokop/SwiftConcurrentCollections\" ~> 1.3.0" >> Cartfile (or use nano)
  • Run carthage update
  • Add SwiftConcurrentCollections to your carthage copy-frameworks phase
  • Add import SwiftConcurrentCollections in files where you plan to use it

Usage

Do import SwiftConcurrentCollections

Then you can use concurrent collections from different threads without fear of crashes or data corruption

let concurrentArray = ConcurrentArray<Int>()
concurrentArray.append(value)
print(concurrentArray[0])
let concurrentDictionary = ConcurrentDictionary<String, Int>()
concurrentDictionary[key] = value
print(concurrentDictionary[key])

Safe subscript

Safe array subscript: for atomicity of checking if specified index is in the array and getting element with that index use

if let element = concurrentArray[safe: index] {
    // ...
}

instead of

if index < concurrentArray.count {
    let element = concurrentArray[index]
    // ...
}

Priority queue

SCC provides both classical and concurrent priority queues

var priorityQueue = PriorityQueue<Int>(<)

priorityQueue.insert(3)
priorityQueue.insert(2)
priorityQueue.insert(1)

while priorityQueue.count > 0 {
    print(
        priorityQueue.pop(),
        terminator: " "
    )
    // Will print: 1 2 3
}

As you can see PriorityQueue<Int>(<) constructs min-queue, with PriorityQueue<Int>(>) you can get max-queue. If you need to reserve capacity right away, use PriorityQueue<Int>(capacity: 1024, comparator: <). ConcurrentPriorityQueue<Int>(<) creates a thread-safe version, with a very similar interface.

swiftconcurrentcollections's People

Contributors

hstdt avatar peterprokop avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

swiftconcurrentcollections's Issues

Locking bug in the ConcurrentDictionary implementation?

I believe there's a bug in the implementation of ConcurrentDictionary:

public subscript(key: Key) -> Value? {
   get {
      return value(forKey: key)
   }
   set {
      rwlock.writeLock()
      guard let newValue = newValue else {
          _remove(key)
          return
      }
      _set(value: newValue, forKey: key)
      rwlock.unlock()
   }
}

If the new value being assigned to a specific dictionary key happens to be nil, then rwlock.writeLock() is called but the setter returns without calling rwlock.unlock(). So the ConcurrentDictionary will remain locked and all subsequent access attempts will block (forever).

A solution is to add a defer{ } block which will be guaranteed to call rwlock.unlock() no matter how the setter exits, as follows:

public subscript(key: Key) -> Value? {
    get {
       return value(forKey: key)
    }
    set {
        rwlock.writeLock()
        defer {
            rwlock.unlock()
        }
        guard let newValue = newValue else {
            _remove(key)
            return
        }
        _set(value: newValue, forKey: key)
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.