diff --git a/IntegrationTests/tests_05_assertions/test_01_syscall_wrapper_fast.sh b/IntegrationTests/tests_05_assertions/test_01_syscall_wrapper_fast.sh index c5d2ff4e1..d3d366f18 100644 --- a/IntegrationTests/tests_05_assertions/test_01_syscall_wrapper_fast.sh +++ b/IntegrationTests/tests_05_assertions/test_01_syscall_wrapper_fast.sh @@ -26,14 +26,14 @@ elif [[ "$(uname -s)" == "Linux" ]]; then swift_binary=$(which swiftc) fi -cp "$here/../../Sources/NIOConcurrencyHelpers/lock.swift" "$tmp" +cp "$here/../../Sources/NIOConcurrencyHelpers/"{lock,NIOLock}.swift "$tmp" cat > "$tmp/main.swift" <<"EOF" -let l = Lock() +let l = NIOLock() l.lock() l.lock() EOF -"$swift_binary" -o "$tmp/test" "$tmp/main.swift" "$tmp/lock.swift" +"$swift_binary" -o "$tmp/test" "$tmp/main.swift" "$tmp/"{lock,NIOLock}.swift if "$tmp/test"; then fail "should have crashed" else diff --git a/Sources/NIOConcurrencyHelpers/LockedValue.swift b/Sources/NIOConcurrencyHelpers/LockedValue.swift index f8239b19f..feeaadb29 100644 --- a/Sources/NIOConcurrencyHelpers/LockedValue.swift +++ b/Sources/NIOConcurrencyHelpers/LockedValue.swift @@ -25,7 +25,7 @@ public struct NIOLockedValueBox { @usableFromInline internal final class _Storage { @usableFromInline - internal let _lock = Lock() + internal let _lock = NIOLock() @usableFromInline internal var _value: Value diff --git a/Sources/NIOConcurrencyHelpers/NIOLock.swift b/Sources/NIOConcurrencyHelpers/NIOLock.swift new file mode 100644 index 000000000..3f1c9f6df --- /dev/null +++ b/Sources/NIOConcurrencyHelpers/NIOLock.swift @@ -0,0 +1,148 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2022 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +import Darwin +#elseif os(Windows) +import ucrt +import WinSDK +#else +import Glibc +#endif + +/// A threading lock based on `libpthread` instead of `libdispatch`. +/// +/// - note: ``NIOLock`` has reference semantics. +/// +/// This object provides a lock on top of a single `pthread_mutex_t`. This kind +/// of lock is safe to use with `libpthread`-based threading models, such as the +/// one used by NIO. On Windows, the lock is based on the substantially similar +/// `SRWLOCK` type. +public struct NIOLock { + @usableFromInline + internal let _storage: _Storage + +#if os(Windows) + @usableFromInline + internal typealias LockPrimitive = SRWLOCK +#else + @usableFromInline + internal typealias LockPrimitive = pthread_mutex_t +#endif + + @usableFromInline + internal final class _Storage { + // TODO: We should tail-allocate the pthread_t/SRWLock. + @usableFromInline + internal let mutex: UnsafeMutablePointer = + UnsafeMutablePointer.allocate(capacity: 1) + + /// Create a new lock. + internal init() { +#if os(Windows) + InitializeSRWLock(self.mutex) +#else + var attr = pthread_mutexattr_t() + pthread_mutexattr_init(&attr) + debugOnly { + pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK)) + } + + let err = pthread_mutex_init(self.mutex, &attr) + precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") +#endif + } + + internal func lock() { +#if os(Windows) + AcquireSRWLockExclusive(self.mutex) +#else + let err = pthread_mutex_lock(self.mutex) + precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") +#endif + } + + internal func unlock() { +#if os(Windows) + ReleaseSRWLockExclusive(self._storage.mutex) +#else + let err = pthread_mutex_unlock(self.mutex) + precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") +#endif + } + + internal func withLockPrimitive(_ body: (UnsafeMutablePointer) throws -> T) rethrows -> T { + return try body(self.mutex) + } + + deinit { +#if os(Windows) + // SRWLOCK does not need to be free'd +#else + let err = pthread_mutex_destroy(self.mutex) + precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)") +#endif + mutex.deallocate() + } + } + + /// Create a new lock. + public init() { + self._storage = _Storage() + } + + /// Acquire the lock. + /// + /// Whenever possible, consider using `withLock` instead of this method and + /// `unlock`, to simplify lock handling. + public func lock() { + self._storage.lock() + } + + /// Release the lock. + /// + /// Whenever possible, consider using `withLock` instead of this method and + /// `lock`, to simplify lock handling. + public func unlock() { + self._storage.unlock() + } + + internal func withLockPrimitive(_ body: (UnsafeMutablePointer) throws -> T) rethrows -> T { + return try self._storage.withLockPrimitive(body) + } +} + +extension NIOLock { + /// Acquire the lock for the duration of the given block. + /// + /// This convenience method should be preferred to `lock` and `unlock` in + /// most situations, as it ensures that the lock will be released regardless + /// of how `body` exits. + /// + /// - Parameter body: The block to execute while holding the lock. + /// - Returns: The value returned by the block. + @inlinable + public func withLock(_ body: () throws -> T) rethrows -> T { + self.lock() + defer { + self.unlock() + } + return try body() + } +} + +#if compiler(>=5.5) && canImport(_Concurrency) +extension NIOLock: Sendable {} +extension NIOLock._Storage: Sendable {} +#endif diff --git a/Sources/NIOConcurrencyHelpers/lock.swift b/Sources/NIOConcurrencyHelpers/lock.swift index 1d0a16739..124d400d7 100644 --- a/Sources/NIOConcurrencyHelpers/lock.swift +++ b/Sources/NIOConcurrencyHelpers/lock.swift @@ -27,6 +27,7 @@ import Glibc /// of lock is safe to use with `libpthread`-based threading models, such as the /// one used by NIO. On Windows, the lock is based on the substantially similar /// `SRWLOCK` type. +@available(*, deprecated, renamed: "NIOLock") public final class Lock { #if os(Windows) fileprivate let mutex: UnsafeMutablePointer = @@ -89,6 +90,7 @@ public final class Lock { } } +@available(*, deprecated, renamed: "NIOLock") extension Lock { /// Acquire the lock for the duration of the given block. /// @@ -120,7 +122,7 @@ extension Lock { /// until the state variable is set to a specific value to acquire the lock. public final class ConditionLock { private var _value: T - private let mutex: Lock + private let mutex: NIOLock #if os(Windows) private let cond: UnsafeMutablePointer = UnsafeMutablePointer.allocate(capacity: 1) @@ -134,7 +136,7 @@ public final class ConditionLock { /// - Parameter value: The initial value to give the state variable. public init(value: T) { self._value = value - self.mutex = Lock() + self.mutex = NIOLock() #if os(Windows) InitializeConditionVariable(self.cond) #else @@ -186,13 +188,15 @@ public final class ConditionLock { if self._value == wantedValue { break } + self.mutex.withLockPrimitive { mutex in #if os(Windows) - let result = SleepConditionVariableSRW(self.cond, self.mutex.mutex, INFINITE, 0) - precondition(result, "\(#function) failed in SleepConditionVariableSRW with error \(GetLastError())") + let result = SleepConditionVariableSRW(self.cond, mutex, INFINITE, 0) + precondition(result, "\(#function) failed in SleepConditionVariableSRW with error \(GetLastError())") #else - let err = pthread_cond_wait(self.cond, self.mutex.mutex) - precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") + let err = pthread_cond_wait(self.cond, mutex) + precondition(err == 0, "\(#function) failed in pthread_cond with error \(err)") #endif + } } } @@ -244,18 +248,20 @@ public final class ConditionLock { tv_nsec: Int(allNSecs % nsecPerSec)) assert(timeoutAbs.tv_nsec >= 0 && timeoutAbs.tv_nsec < Int(nsecPerSec)) assert(timeoutAbs.tv_sec >= curTime.tv_sec) - while true { - if self._value == wantedValue { - return true - } - switch pthread_cond_timedwait(self.cond, self.mutex.mutex, &timeoutAbs) { - case 0: - continue - case ETIMEDOUT: - self.unlock() - return false - case let e: - fatalError("caught error \(e) when calling pthread_cond_timedwait") + return self.mutex.withLockPrimitive { mutex -> Bool in + while true { + if self._value == wantedValue { + return true + } + switch pthread_cond_timedwait(self.cond, mutex, &timeoutAbs) { + case 0: + continue + case ETIMEDOUT: + self.unlock() + return false + case let e: + fatalError("caught error \(e) when calling pthread_cond_timedwait") + } } } #endif @@ -288,6 +294,7 @@ internal func debugOnly(_ body: () -> Void) { } #if compiler(>=5.5) && canImport(_Concurrency) +@available(*, deprecated, renamed: "NIOLock") extension Lock: Sendable { } diff --git a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift index 43961aaa0..8f9306eb0 100644 --- a/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift +++ b/Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift @@ -395,7 +395,7 @@ extension NIOAsyncWriter { /// The lock that protects our state. @usableFromInline - /* private */ internal let _lock = Lock() + /* private */ internal let _lock = NIOLock() /// The counter used to assign an ID to all our yields. @usableFromInline /* private */ internal let _yieldIDGenerator = YieldIDGenerator() diff --git a/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift b/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift index 2bea7738f..20904215c 100644 --- a/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift +++ b/Sources/NIOCore/AsyncSequences/NIOThrowingAsyncSequenceProducer.swift @@ -304,7 +304,7 @@ extension NIOThrowingAsyncSequenceProducer { /* fileprivate */ internal final class Storage: @unchecked Sendable { /// The lock that protects our state. @usableFromInline - /* private */ internal let _lock = Lock() + /* private */ internal let _lock = NIOLock() /// The state machine. @usableFromInline /* private */ internal var _stateMachine: StateMachine diff --git a/Sources/NIOCore/EventLoop.swift b/Sources/NIOCore/EventLoop.swift index cac7d23d9..28e8ab1d8 100644 --- a/Sources/NIOCore/EventLoop.swift +++ b/Sources/NIOCore/EventLoop.swift @@ -1186,7 +1186,7 @@ extension EventLoopGroup { public func syncShutdownGracefully() throws { self._preconditionSafeToSyncShutdown(file: #file, line: #line) - let errorStorageLock = Lock() + let errorStorageLock = NIOLock() var errorStorage: Error? = nil let continuation = DispatchWorkItem {} self.shutdownGracefully { error in diff --git a/Sources/NIOEmbedded/AsyncTestingChannel.swift b/Sources/NIOEmbedded/AsyncTestingChannel.swift index f77af801c..3e111a322 100644 --- a/Sources/NIOEmbedded/AsyncTestingChannel.swift +++ b/Sources/NIOEmbedded/AsyncTestingChannel.swift @@ -194,7 +194,7 @@ public final class NIOAsyncTestingChannel: Channel { /*private but usableFromInline */ var channelcore: EmbeddedChannelCore! /// Guards any of the getters/setters that can be accessed from any thread. - private let stateLock: Lock = Lock() + private let stateLock: NIOLock = NIOLock() // Guarded by `stateLock` private var _isWritable: Bool = true @@ -223,7 +223,7 @@ public final class NIOAsyncTestingChannel: Channel { return self.stateLock.withLock { self._isWritable } } set { - self.stateLock.withLockVoid { + self.stateLock.withLock { () -> Void in self._isWritable = newValue } } @@ -235,7 +235,7 @@ public final class NIOAsyncTestingChannel: Channel { return self.stateLock.withLock { self._localAddress } } set { - self.stateLock.withLockVoid { + self.stateLock.withLock { () -> Void in self._localAddress = newValue } } @@ -247,7 +247,7 @@ public final class NIOAsyncTestingChannel: Channel { return self.stateLock.withLock { self._remoteAddress } } set { - self.stateLock.withLockVoid { + self.stateLock.withLock { () -> Void in self._remoteAddress = newValue } } diff --git a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift index 723b1d22c..b0620e9e1 100644 --- a/Sources/NIOEmbedded/AsyncTestingEventLoop.swift +++ b/Sources/NIOEmbedded/AsyncTestingEventLoop.swift @@ -353,12 +353,12 @@ public final class NIOAsyncTestingEventLoop: EventLoop, @unchecked Sendable { /// /// We use this to keep track of where promises come from in the `NIOAsyncTestingEventLoop`. private class PromiseCreationStore { - private let lock = Lock() + private let lock = NIOLock() private var promiseCreationStore: [_NIOEventLoopFutureIdentifier: (file: StaticString, line: UInt)] = [:] func promiseCreated(futureIdentifier: _NIOEventLoopFutureIdentifier, file: StaticString, line: UInt) { precondition(_isDebugAssertConfiguration()) - self.lock.withLockVoid { + self.lock.withLock { () -> Void in self.promiseCreationStore[futureIdentifier] = (file: file, line: line) } } diff --git a/Sources/NIOPerformanceTester/LockBenchmark.swift b/Sources/NIOPerformanceTester/LockBenchmark.swift index 0315acb98..114062bc5 100644 --- a/Sources/NIOPerformanceTester/LockBenchmark.swift +++ b/Sources/NIOPerformanceTester/LockBenchmark.swift @@ -17,7 +17,7 @@ import NIOPosix import Dispatch import NIOConcurrencyHelpers -final class LockBenchmark: Benchmark { +final class NIOLockBenchmark: Benchmark { private let numberOfThreads: Int private let lockOperationsPerThread: Int private let threadPool: NIOThreadPool @@ -27,7 +27,7 @@ final class LockBenchmark: Benchmark { private let sem3 = DispatchSemaphore(value: 0) private var opsDone = 0 - private let lock = Lock() + private let lock = NIOLock() init(numberOfThreads: Int, lockOperationsPerThread: Int) { self.numberOfThreads = numberOfThreads diff --git a/Sources/NIOPerformanceTester/main.swift b/Sources/NIOPerformanceTester/main.swift index f3c0568e4..07b0f95a7 100644 --- a/Sources/NIOPerformanceTester/main.swift +++ b/Sources/NIOPerformanceTester/main.swift @@ -1016,7 +1016,7 @@ try measureAndPrint( try measureAndPrint( desc: "lock_1_thread_10M_ops", - benchmark: LockBenchmark( + benchmark: NIOLockBenchmark( numberOfThreads: 1, lockOperationsPerThread: 10_000_000 ) @@ -1024,7 +1024,7 @@ try measureAndPrint( try measureAndPrint( desc: "lock_2_threads_10M_ops", - benchmark: LockBenchmark( + benchmark: NIOLockBenchmark( numberOfThreads: 2, lockOperationsPerThread: 5_000_000 ) @@ -1032,7 +1032,7 @@ try measureAndPrint( try measureAndPrint( desc: "lock_4_threads_10M_ops", - benchmark: LockBenchmark( + benchmark: NIOLockBenchmark( numberOfThreads: 4, lockOperationsPerThread: 2_500_000 ) @@ -1041,7 +1041,7 @@ try measureAndPrint( try measureAndPrint( desc: "lock_8_threads_10M_ops", - benchmark: LockBenchmark( + benchmark: NIOLockBenchmark( numberOfThreads: 8, lockOperationsPerThread: 1_250_000 ) diff --git a/Sources/NIOPosix/BaseSocketChannel.swift b/Sources/NIOPosix/BaseSocketChannel.swift index 0d674c6cb..7b5d1870a 100644 --- a/Sources/NIOPosix/BaseSocketChannel.swift +++ b/Sources/NIOPosix/BaseSocketChannel.swift @@ -238,7 +238,7 @@ class BaseSocketChannel: SelectableChannel, Chan internal let socket: SocketType private let closePromise: EventLoopPromise internal let selectableEventLoop: SelectableEventLoop - private let _offEventLoopLock = Lock() + private let _offEventLoopLock = NIOLock() private let isActiveAtomic: ManagedAtomic = .init(false) // just a thread-safe way of having something to print about the socket from any thread internal let socketDescription: String diff --git a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift index 12a4b684f..f2ded61ce 100644 --- a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift +++ b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift @@ -70,7 +70,7 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { private let myGroupID: Int private let index = ManagedAtomic(0) private var eventLoops: [SelectableEventLoop] - private let shutdownLock: Lock = Lock() + private let shutdownLock: NIOLock = NIOLock() private var runState: RunState = .running private static func runTheLoop(thread: NIOThread, @@ -104,7 +104,7 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { parentGroup: MultiThreadedEventLoopGroup, selectorFactory: @escaping () throws -> NIOPosix.Selector, initializer: @escaping ThreadInitializer) -> SelectableEventLoop { - let lock = Lock() + let lock = NIOLock() /* the `loopUpAndRunningGroup` is done by the calling thread when the EventLoop has been created and was written to `_loop` */ let loopUpAndRunningGroup = DispatchGroup() diff --git a/Sources/NIOPosix/NIOThreadPool.swift b/Sources/NIOPosix/NIOThreadPool.swift index d0f240927..8a69b71fc 100644 --- a/Sources/NIOPosix/NIOThreadPool.swift +++ b/Sources/NIOPosix/NIOThreadPool.swift @@ -65,7 +65,7 @@ public final class NIOThreadPool { case running(CircularBuffer) } private let semaphore = DispatchSemaphore(value: 0) - private let lock = Lock() + private let lock = NIOLock() private var threads: [NIOThread]? = nil // protected by `lock` private var state: State = .stopped private let numberOfThreads: Int @@ -313,7 +313,7 @@ extension NIOThreadPool { #endif public func syncShutdownGracefully() throws { - let errorStorageLock = Lock() + let errorStorageLock = NIOLock() var errorStorage: Swift.Error? = nil let continuation = DispatchWorkItem {} self.shutdownGracefully { error in diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index e1791f285..1383438e3 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -90,9 +90,9 @@ internal final class SelectableEventLoop: EventLoop { private let canBeShutdownIndividually: Bool @usableFromInline - internal let _tasksLock = Lock() - private let _externalStateLock = Lock() - private var externalStateLock: Lock { + internal let _tasksLock = NIOLock() + private let _externalStateLock = NIOLock() + private var externalStateLock: NIOLock { // The assert is here to check that we never try to read the external state on the EventLoop unless we're // shutting down. assert(!self.inEventLoop || self.internalState != .runningAndAcceptingNewRegistrations, @@ -123,7 +123,7 @@ internal final class SelectableEventLoop: EventLoop { /// Creates a new `SelectableEventLoop` instance that is tied to the given `pthread_t`. - private let promiseCreationStoreLock = Lock() + private let promiseCreationStoreLock = NIOLock() private var _promiseCreationStore: [_NIOEventLoopFutureIdentifier: (file: StaticString, line: UInt)] = [:] @usableFromInline @@ -289,7 +289,7 @@ Further information: let taskId = task.id let scheduled = Scheduled(promise: promise, cancellationTask: { - self._tasksLock.withLockVoid { + self._tasksLock.withLock { () -> Void in self._scheduledTasks.removeFirst(where: { $0.id == taskId }) } // We don't need to wake up the selector here, the scheduled task will never be picked up. Waking up the @@ -330,7 +330,7 @@ Further information: precondition(self._validInternalStateToScheduleTasks, "BUG IN NIO (please report): EventLoop is shutdown, yet we're on the EventLoop.") - self._tasksLock.withLockVoid { + self._tasksLock.withLock { () -> Void in self._scheduledTasks.push(task) } } else { @@ -440,7 +440,7 @@ Further information: repeat { // We may need to do multiple rounds of this because failing tasks may lead to more work. scheduledTasksCopy.removeAll(keepingCapacity: true) - self._tasksLock.withLockVoid { + self._tasksLock.withLock { () -> Void in // In this state we never want the selector to be woken again, so we pretend we're permanently running. self._pendingTaskPop = true @@ -479,7 +479,7 @@ Further information: try withAutoReleasePool { try self._selector.whenReady( strategy: currentSelectorStrategy(nextReadyTask: nextReadyTask), - onLoopBegin: { self._tasksLock.withLockVoid { self._pendingTaskPop = true } } + onLoopBegin: { self._tasksLock.withLock { () -> Void in self._pendingTaskPop = true } } ) { ev in switch ev.registration.channel { case .serverSocketChannel(let chan): @@ -504,7 +504,7 @@ Further information: // We need to ensure we process all tasks, even if a task added another task again while true { // TODO: Better locking - self._tasksLock.withLockVoid { + self._tasksLock.withLock { () -> Void in if !self._scheduledTasks.isEmpty { // We only fetch the time one time as this may be expensive and is generally good enough as if we miss anything we will just do a non-blocking select again anyway. let now: NIODeadline = .now() diff --git a/Sources/NIOPosix/SelectorGeneric.swift b/Sources/NIOPosix/SelectorGeneric.swift index 9fb859774..abb7876e4 100644 --- a/Sources/NIOPosix/SelectorGeneric.swift +++ b/Sources/NIOPosix/SelectorGeneric.swift @@ -131,7 +131,7 @@ internal class Selector { // The rules for `self.selectorFD`, `self.eventFD`, and `self.timerFD`: // reads: `self.externalSelectorFDLock` OR access from the EventLoop thread // writes: `self.externalSelectorFDLock` AND access from the EventLoop thread - let externalSelectorFDLock = Lock() + let externalSelectorFDLock = NIOLock() var selectorFD: CInt = -1 // -1 == we're closed // Here we add the stored properties that are used by the specific backends diff --git a/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift b/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift index 267fe0aa5..f685dad64 100644 --- a/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift +++ b/Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift @@ -461,7 +461,7 @@ class NIOConcurrencyHelpersTests: XCTestCase { func testLockMutualExclusion() { - let l = Lock() + let l = NIOLock() var x = 1 let q = DispatchQueue(label: "q") @@ -493,7 +493,7 @@ class NIOConcurrencyHelpersTests: XCTestCase { } func testWithLockMutualExclusion() { - let l = Lock() + let l = NIOLock() var x = 1 let q = DispatchQueue(label: "q") diff --git a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift index a65b506b3..f3076374e 100644 --- a/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift +++ b/Tests/NIOEmbeddedTests/AsyncTestingEventLoopTests.swift @@ -453,7 +453,7 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { // schedule that expire "now" all run at the same time, and that any work they schedule is run // after all such tasks expire. let loop = NIOAsyncTestingEventLoop() - let lock = Lock() + let lock = NIOLock() var firstScheduled: Scheduled? = nil var secondScheduled: Scheduled? = nil let orderingCounter = ManagedAtomic(0) @@ -472,7 +472,7 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { // // To validate the ordering, we'll use a counter. - lock.withLockVoid { + lock.withLock { () -> Void in firstScheduled = loop.scheduleTask(in: .nanoseconds(5)) { let second = lock.withLock { () -> Scheduled? in XCTAssertNotNil(firstScheduled) @@ -496,7 +496,7 @@ final class NIOAsyncTestingEventLoopTests: XCTestCase { } secondScheduled = loop.scheduleTask(in: .nanoseconds(5)) { - lock.withLockVoid { + lock.withLock { () -> Void in secondScheduled = nil XCTAssertNil(firstScheduled) XCTAssertNil(secondScheduled) diff --git a/Tests/NIOEmbeddedTests/TestUtils.swift b/Tests/NIOEmbeddedTests/TestUtils.swift index 3357b0a72..86d35774e 100644 --- a/Tests/NIOEmbeddedTests/TestUtils.swift +++ b/Tests/NIOEmbeddedTests/TestUtils.swift @@ -43,7 +43,7 @@ extension EventLoopFuture { } return fulfilled } else { - let lock = Lock() + let lock = NIOLock() let group = DispatchGroup() var fulfilled = false // protected by lock diff --git a/Tests/NIOPosixTests/BootstrapTest.swift b/Tests/NIOPosixTests/BootstrapTest.swift index 72533f7a4..640529ba4 100644 --- a/Tests/NIOPosixTests/BootstrapTest.swift +++ b/Tests/NIOPosixTests/BootstrapTest.swift @@ -21,7 +21,7 @@ import XCTest class BootstrapTest: XCTestCase { var group: MultiThreadedEventLoopGroup! var groupBag: [MultiThreadedEventLoopGroup]? = nil // protected by `self.lock` - let lock = Lock() + let lock = NIOLock() override func setUp() { XCTAssertNil(self.group) diff --git a/Tests/NIOPosixTests/EventLoopTest.swift b/Tests/NIOPosixTests/EventLoopTest.swift index 4191698db..d7d5775c6 100644 --- a/Tests/NIOPosixTests/EventLoopTest.swift +++ b/Tests/NIOPosixTests/EventLoopTest.swift @@ -1164,7 +1164,7 @@ public final class EventLoopTest : XCTestCase { func testTakeOverThreadAndAlsoTakeItBack() { let currentNIOThread = NIOThread.current let currentNSThread = Thread.current - let lock = Lock() + let lock = NIOLock() var hasBeenShutdown = false let allDoneGroup = DispatchGroup() allDoneGroup.enter() diff --git a/Tests/NIOPosixTests/NIOThreadPoolTest.swift b/Tests/NIOPosixTests/NIOThreadPoolTest.swift index f3ac48531..de80538ca 100644 --- a/Tests/NIOPosixTests/NIOThreadPoolTest.swift +++ b/Tests/NIOPosixTests/NIOThreadPoolTest.swift @@ -27,7 +27,7 @@ class NIOThreadPoolTest: XCTestCase { } var allThreadNames: Set = [] - let lock = Lock() + let lock = NIOLock() let threadNameCollectionSem = DispatchSemaphore(value: 0) let threadBlockingSem = DispatchSemaphore(value: 0) @@ -74,14 +74,14 @@ class NIOThreadPoolTest: XCTestCase { // The lock here is arguably redundant with the dispatchgroup, but let's make // this test thread-safe even if I screw up. - let lock = Lock() + let lock = NIOLock() var threadOne = Thread?.none var threadTwo = Thread?.none completionGroup.enter() pool.submit { s in precondition(s == .active) - lock.withLockVoid { + lock.withLock { () -> Void in XCTAssertEqual(threadOne, nil) threadOne = Thread.current } @@ -93,7 +93,7 @@ class NIOThreadPoolTest: XCTestCase { completionGroup.enter() pool.submit { s in precondition(s == .active) - lock.withLockVoid { + lock.withLock { () -> Void in XCTAssertEqual(threadTwo, nil) threadTwo = Thread.current } @@ -102,7 +102,7 @@ class NIOThreadPoolTest: XCTestCase { completionGroup.wait() - lock.withLockVoid { + lock.withLock { () -> Void in XCTAssertNotNil(threadOne) XCTAssertNotNil(threadTwo) XCTAssertEqual(threadOne, threadTwo) diff --git a/Tests/NIOPosixTests/TestUtils.swift b/Tests/NIOPosixTests/TestUtils.swift index 745210e07..0e8a08255 100644 --- a/Tests/NIOPosixTests/TestUtils.swift +++ b/Tests/NIOPosixTests/TestUtils.swift @@ -496,7 +496,7 @@ func forEachActiveChannelType(file: StaticString = #file, } let channelEL = group.next() - let lock = Lock() + let lock = NIOLock() var ret: [T] = [] _ = try forEachCrossConnectedStreamChannelPair(file: (file), line: line) { (chan1: Channel, chan2: Channel) throws -> Void in var innerRet: [T] = [try body(chan1)] @@ -692,7 +692,7 @@ extension EventLoopFuture { } return fulfilled } else { - let lock = Lock() + let lock = NIOLock() let group = DispatchGroup() var fulfilled = false // protected by lock diff --git a/Tests/NIOPosixTests/ThreadTest.swift b/Tests/NIOPosixTests/ThreadTest.swift index eed3bf4e0..396ca3ea0 100644 --- a/Tests/NIOPosixTests/ThreadTest.swift +++ b/Tests/NIOPosixTests/ThreadTest.swift @@ -260,7 +260,7 @@ class ThreadTest: XCTestCase { } } var globalTSVs: [ThreadSpecificVariable] = [] - let globalTSVLock = Lock() + let globalTSVLock = NIOLock() ({ let tsv = ThreadSpecificVariable() globalTSVLock.withLock {