Skip to content

Commit

Permalink
Gurantee ordering of scheduleTask with same deadline
Browse files Browse the repository at this point in the history
### Motivation:

When scheduling tasks with the same deadline the current order of execution is undefined. Fixes apple#1541

### Modifications:

In my previous PR apple#2010, I added an internal id to every `ScheduledTask` to give them an identity for cancellation purposes. In this PR, I am now using the same id to also ensure that the execution of tasks with the same deadline is the same as the order they were scheduled in.

### Result:

`ScheduledTask`s are now executed in their scheduled order when they have the same deadline.
  • Loading branch information
FranzBusch committed Dec 27, 2021
1 parent acbd697 commit beb6467
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Sources/NIOPosix/MultiThreadedEventLoopGroup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,11 @@ extension ScheduledTask: CustomStringConvertible {
extension ScheduledTask: Comparable {
@usableFromInline
static func < (lhs: ScheduledTask, rhs: ScheduledTask) -> Bool {
return lhs._readyTime < rhs._readyTime
if lhs._readyTime == rhs._readyTime {
return lhs.id < rhs.id
} else {
return lhs._readyTime < rhs._readyTime
}
}

@usableFromInline
Expand Down
20 changes: 20 additions & 0 deletions Tests/NIOPosixTests/EventLoopTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,26 @@ public final class EventLoopTest : XCTestCase {
XCTAssertEqual(error as? EventLoopError, .cancelled)
}

public func testScheduledTasksAreOrdered() throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
}

let eventLoop = eventLoopGroup.next()
let now = NIODeadline.now()

var result = [Int]()
var lastScheduled: Scheduled<Void>?
for i in 0...100 {
lastScheduled = eventLoop.scheduleTask(deadline: now) {
result.append(i)
}
}
try lastScheduled?.futureResult.wait()
XCTAssertEqual(result, Array(0...100))
}

public func testFlatScheduledTaskThatIsImmediatelyCancelledNeverFires() throws {
let eventLoop = EmbeddedEventLoop()
let scheduled = eventLoop.flatScheduleTask(in: .seconds(1)) {
Expand Down

0 comments on commit beb6467

Please sign in to comment.