项目作者: peterprokop

项目描述 :
Swift Concurrent Collections
高级语言: Swift
项目地址: git://github.com/peterprokop/SwiftConcurrentCollections.git
创建时间: 2020-02-03T14:38:47Z
项目社区:https://github.com/peterprokop/SwiftConcurrentCollections

开源协议:MIT License

下载


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.

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

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

  1. let concurrentArray = ConcurrentArray<Int>()
  2. concurrentArray.append(value)
  3. print(concurrentArray[0])
  1. let concurrentDictionary = ConcurrentDictionary<String, Int>()
  2. concurrentDictionary[key] = value
  3. 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

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

instead of

  1. if index < concurrentArray.count {
  2. let element = concurrentArray[index]
  3. // ...
  4. }

Priority queue

SCC provides both classical and concurrent priority queues

  1. var priorityQueue = PriorityQueue<Int>(<)
  2. priorityQueue.insert(3)
  3. priorityQueue.insert(2)
  4. priorityQueue.insert(1)
  5. while priorityQueue.count > 0 {
  6. print(
  7. priorityQueue.pop(),
  8. terminator: " "
  9. )
  10. // Will print: 1 2 3
  11. }

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.