From ba077d3be8a833faeb5924b9ecf9a942bfafa690 Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Fri, 13 Jul 2018 18:13:13 +0100 Subject: [PATCH] fix two tests threading issues (#513) Motivation: testScheduleRepeatedTask and testScheduleRepeatedTaskCancelFromDifferentThread has threading issues that I unfortunately missed in review. Modifications: fix the threading issues by using a `DispatchGroup` Result: fewer theading issues in the tests --- Tests/NIOTests/EventLoopTest.swift | 32 +++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/Tests/NIOTests/EventLoopTest.swift b/Tests/NIOTests/EventLoopTest.swift index 14480b324..43bf4f9c5 100644 --- a/Tests/NIOTests/EventLoopTest.swift +++ b/Tests/NIOTests/EventLoopTest.swift @@ -103,16 +103,28 @@ public class EventLoopTest : XCTestCase { let expect = expectation(description: "Is cancelling RepatedTask") let counter = Atomic(value: 0) - var repeatedTask: RepeatedTask? - repeatedTask = eventLoopGroup.next().scheduleRepeatedTask(initialDelay: initialDelay, delay: delay) { () -> Void in + let lock = Lock() + var repeatedTask: RepeatedTask? = nil // protected by `lock` + let task = eventLoopGroup.next().scheduleRepeatedTask(initialDelay: initialDelay, delay: delay) { () -> Void in if counter.load() == 0 { XCTAssertTrue(DispatchTime.now().uptimeNanoseconds - nanos >= initialDelay.nanoseconds) } else if counter.load() == count { expect.fulfill() - repeatedTask?.cancel() + while true { + let mTask = lock.withLock { repeatedTask } + guard let task = mTask else { + usleep(10_000) + continue + } + task.cancel() + break + } } counter.store(counter.load() + 1) } + lock.withLock { + repeatedTask = task + } waitForExpectations(timeout: 1) { _ in XCTAssertEqual(counter.load(), count + 1) @@ -130,12 +142,14 @@ public class EventLoopTest : XCTestCase { } let expect = expectation(description: "Is cancelling RepatedTask") - var repeatedTask: RepeatedTask? - repeatedTask = eventLoopGroup.next().scheduleRepeatedTask(initialDelay: initialDelay, delay: delay) { () -> Void in - DispatchQueue(label: "nio.repeatedtask.test").async { - repeatedTask?.cancel() - expect.fulfill() - } + let group = DispatchGroup() + group.enter() + let repeatedTask = eventLoopGroup.next().scheduleRepeatedTask(initialDelay: initialDelay, delay: delay) { () -> Void in + group.leave() + expect.fulfill() + } + group.notify(queue: DispatchQueue.global()) { + repeatedTask.cancel() } waitForExpectations(timeout: 1) { _ in