Skip to content

Commit

Permalink
Make CompletedCondtion optional, should improve memory usage slightly.
Browse files Browse the repository at this point in the history
  • Loading branch information
richardjrossiii committed Jun 1, 2016
1 parent af1ec49 commit 24daec3
Showing 1 changed file with 29 additions and 7 deletions.
36 changes: 29 additions & 7 deletions Sources/BoltsSwift/Task.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public final class Task<TResult> {
public typealias Continuation = () -> Void

private let synchronizationQueue = dispatch_queue_create("com.bolts.task", DISPATCH_QUEUE_CONCURRENT)
private let completedCondition = NSCondition()
private var _completedCondition: NSCondition?

private var _state: TaskState<TResult> = .Pending()
private var _continuations: [Continuation] = Array()
Expand Down Expand Up @@ -209,11 +209,13 @@ public final class Task<TResult> {
if completed {
return
}
completedCondition.lock()
let condition = completedCondition
condition?.lock()
while !completed {
completedCondition.wait()
condition?.wait()
}
completedCondition.unlock()
condition?.unlock()
completedCondition = nil
}

// MARK: State Change
Expand All @@ -222,21 +224,23 @@ public final class Task<TResult> {
var stateChanged = false

var continuations: [Continuation]?
var completedCondition: NSCondition?
dispatch_barrier_sync(synchronizationQueue) {
switch self._state {
case .Pending():
stateChanged = true
self._state = state
continuations = self._continuations
completedCondition = self._completedCondition
self._continuations.removeAll()
default:
break
}
}
if stateChanged {
completedCondition.lock()
completedCondition.broadcast()
completedCondition.unlock()
completedCondition?.lock()
completedCondition?.broadcast()
completedCondition?.unlock()

for continuation in continuations! {
continuation()
Expand Down Expand Up @@ -271,6 +275,24 @@ public final class Task<TResult> {
}
return value!
}

private var completedCondition: NSCondition? {
get {
var value: NSCondition?
dispatch_barrier_sync(synchronizationQueue) {
if self._completedCondition == nil {
self._completedCondition = NSCondition()
}
value = self._completedCondition
}
return value
}
set {
dispatch_barrier_sync(synchronizationQueue) {
self.completedCondition = newValue
}
}
}
}

//--------------------------------------
Expand Down

0 comments on commit 24daec3

Please sign in to comment.