Skip to content

Commit

Permalink
Fixup concurrency
Browse files Browse the repository at this point in the history
  • Loading branch information
SzymonMrozek committed May 23, 2018
1 parent 3ca81bb commit 3cdaa1e
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 38 deletions.
11 changes: 5 additions & 6 deletions Cedric/Cedric.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,10 @@ public class Cedric {
items.forEach {
$0.delegate = nil
$0.cancel()
remove(downloadItem: $0)
$0.releaseReferences()
}

items.removeAll()
}

/// Insert new delegate for multicast
Expand Down Expand Up @@ -186,11 +188,8 @@ public class Cedric {
}

fileprivate func remove(downloadItem item: DownloadItem) {
guard let index = items.index(of: item) else { return }
let item = items[index]

items.remove(at: index)
item?.releaseReferences()
item.releaseReferences()
items.remove(where: { $0 == item })

guard items.isEmpty else { return }
delegates.invoke({ $0.cedric(self, didFinishWithMostRecentError: self.lastError) })
Expand Down
35 changes: 3 additions & 32 deletions Cedric/ConcurrentArray.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,42 +75,17 @@ extension ConcurrentArray {
self.array.append(element)
}
}

func insert( _ element: T, at index: Int) {
queue.async(flags: .barrier) {
self.array.insert(element, at: index)
}
}

func remove(at index: Int, completion: ((T) -> Void)? = nil) {
queue.async(flags: .barrier) {
let element = self.array.remove(at: index)

DispatchQueue.main.async {
completion?(element)
}
}
}

func remove(where predicate: @escaping (T) -> Bool, completion: ((T) -> Void)? = nil) {
func remove(where predicate: @escaping (T) -> Bool) {
queue.async(flags: .barrier) {
guard let index = self.array.index(where: predicate) else { return }
let element = self.array.remove(at: index)

DispatchQueue.main.async {
completion?(element)
}
self.array.remove(at: index)
}
}

func removeAll(completion: (([T]) -> Void)? = nil) {
func removeAll() {
queue.async(flags: .barrier) {
let elements = self.array
self.array.removeAll()

DispatchQueue.main.async {
completion?(elements)
}
}
}
}
Expand Down Expand Up @@ -144,10 +119,6 @@ extension ConcurrentArray where T: Equatable {
queue.sync { result = self.array.contains(element) }
return result
}

internal func index(of element: T) -> Int? {
return self.index(where: { $0 == element })
}
}

extension ConcurrentArray {
Expand Down

0 comments on commit 3cdaa1e

Please sign in to comment.