diff --git a/Sources/NIO/Thread.swift b/Sources/NIO/Thread.swift index 7ea7e7411..28315e670 100644 --- a/Sources/NIO/Thread.swift +++ b/Sources/NIO/Thread.swift @@ -110,6 +110,59 @@ final class Thread { } } +/// A `ThreadSpecificVariable` is a variable that can be read and set like a normal variable except that it holds +/// different variables per thread. +/// +/// `ThreadSpecificVariable` is thread-safe so it can be used with multiple threads at the same time but the value +/// returned by `currentValue` is defined per thread. +/// +/// - note: `ThreadSpecificVariable` has reference semantics. +internal struct ThreadSpecificVariable { + private let key: pthread_key_t + + /// Initialize a new `ThreadSpecificVariable` without a current value (`currentValue == nil`). + public init() { + var key = pthread_key_t() + let pthreadErr = pthread_key_create(&key) { ptr in + Unmanaged.fromOpaque((ptr as UnsafeMutableRawPointer?)!).release() + } + precondition(pthreadErr == 0, "pthread_key_create failed, error \(pthreadErr)") + self.key = key + } + + /// Initialize a new `ThreadSpecificVariable` with `value` for the calling thread. After calling this, the calling + /// thread will see `currentValue == value` but on all other threads `currentValue` will be `nil` until changed. + /// + /// - parameters: + /// - value: The value to set for the calling thread. + public init(value: T) { + self.init() + self.currentValue = value + } + + /// The value for the current thread. + public var currentValue: T? { + /// Get the current value for the calling thread. + get { + guard let raw = pthread_getspecific(self.key) else { + return nil + } + return Unmanaged.fromOpaque(raw).takeUnretainedValue() + } + + /// Set the current value for the calling threads. The `currentValue` for all other threads remains unchanged. + nonmutating set { + if let raw = pthread_getspecific(self.key) { + Unmanaged.fromOpaque(raw).release() + } + let pthreadErr = pthread_setspecific(self.key, newValue.map { v -> UnsafeMutableRawPointer in + Unmanaged.passRetained(v).toOpaque() + }) + precondition(pthreadErr == 0, "pthread_setspecific failed, error \(pthreadErr)") + } + } +} + extension Thread : Equatable { public static func ==(lhs: Thread, rhs: Thread) -> Bool { return pthread_equal(lhs.pthread, rhs.pthread) != 0 diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 458305849..d901b9cf2 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -64,6 +64,7 @@ import XCTest testCase(SocketChannelTest.allTests), testCase(NIOConcurrencyHelpersTests.allTests), testCase(SystemTest.allTests), + testCase(ThreadTest.allTests), testCase(TypeAssistedChannelHandlerTest.allTests), testCase(UtilitiesTest.allTests), ]) diff --git a/Tests/NIOTests/ThreadTest+XCTest.swift b/Tests/NIOTests/ThreadTest+XCTest.swift new file mode 100644 index 000000000..b7e558610 --- /dev/null +++ b/Tests/NIOTests/ThreadTest+XCTest.swift @@ -0,0 +1,42 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 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 +// +//===----------------------------------------------------------------------===// +/// +/// ThreadTest+XCTest.swift +/// +import XCTest + +/// +/// NOTE: This file was generated by generate_linux_tests.rb +/// +/// Do NOT edit this file directly as it will be regenerated automatically when needed. +/// + +extension ThreadTest { + + static var allTests : [(String, (ThreadTest) -> () throws -> Void)] { + return [ + ("testCurrentThreadWorks", testCurrentThreadWorks), + ("testCurrentThreadIsNotTrueOnOtherThread", testCurrentThreadIsNotTrueOnOtherThread), + ("testThreadSpecificsAreNilWhenNotPresent", testThreadSpecificsAreNilWhenNotPresent), + ("testThreadSpecificsWorks", testThreadSpecificsWorks), + ("testThreadSpecificsAreNotAvailableOnADifferentThread", testThreadSpecificsAreNotAvailableOnADifferentThread), + ("testThreadSpecificDoesNotLeakIfThreadExitsWhilstSet", testThreadSpecificDoesNotLeakIfThreadExitsWhilstSet), + ("testThreadSpecificDoesNotLeakIfThreadExitsAfterUnset", testThreadSpecificDoesNotLeakIfThreadExitsAfterUnset), + ("testThreadSpecificDoesNotLeakIfReplacedWithNewValue", testThreadSpecificDoesNotLeakIfReplacedWithNewValue), + ("testSharingThreadSpecificVariableWorks", testSharingThreadSpecificVariableWorks), + ("testThreadSpecificInitWithValueWorks", testThreadSpecificInitWithValueWorks), + ] + } +} + diff --git a/Tests/NIOTests/ThreadTest.swift b/Tests/NIOTests/ThreadTest.swift new file mode 100644 index 000000000..375217d00 --- /dev/null +++ b/Tests/NIOTests/ThreadTest.swift @@ -0,0 +1,193 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 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 +// +//===----------------------------------------------------------------------===// + +@testable import NIO +import NIOConcurrencyHelpers +import XCTest +import Dispatch + +class ThreadTest: XCTestCase { + func testCurrentThreadWorks() throws { + let s = DispatchSemaphore(value: 0) + Thread.spawnAndRun { t in + XCTAssertTrue(t.isCurrent) + s.signal() + } + s.wait() + } + + func testCurrentThreadIsNotTrueOnOtherThread() throws { + let s = DispatchSemaphore(value: 0) + Thread.spawnAndRun { t1 in + Thread.spawnAndRun { t2 in + XCTAssertFalse(t1.isCurrent) + XCTAssertTrue(t2.isCurrent) + s.signal() + } + } + s.wait() + } + + func testThreadSpecificsAreNilWhenNotPresent() throws { + class SomeClass {} + let s = DispatchSemaphore(value: 0) + Thread.spawnAndRun { _ in + let tsv: ThreadSpecificVariable = ThreadSpecificVariable() + XCTAssertNil(tsv.currentValue) + s.signal() + } + s.wait() + } + + func testThreadSpecificsWorks() throws { + class SomeClass {} + let s = DispatchSemaphore(value: 0) + Thread.spawnAndRun { _ in + let tsv: ThreadSpecificVariable = ThreadSpecificVariable() + XCTAssertNil(tsv.currentValue) + let expected = SomeClass() + tsv.currentValue = expected + XCTAssert(expected === tsv.currentValue) + s.signal() + } + s.wait() + } + + func testThreadSpecificsAreNotAvailableOnADifferentThread() throws { + class SomeClass {} + let s = DispatchSemaphore(value: 0) + Thread.spawnAndRun { _ in + let tsv = ThreadSpecificVariable() + XCTAssertNil(tsv.currentValue) + tsv.currentValue = SomeClass() + XCTAssertNotNil(tsv.currentValue) + Thread.spawnAndRun { t2 in + XCTAssertNil(tsv.currentValue) + s.signal() + } + } + s.wait() + } + + func testThreadSpecificDoesNotLeakIfThreadExitsWhilstSet() throws { + let s = DispatchSemaphore(value: 0) + class SomeClass { + let s: DispatchSemaphore + init(sem: DispatchSemaphore) { self.s = sem } + deinit { + s.signal() + } + } + weak var weakSome: SomeClass? = nil + Thread.spawnAndRun { _ in + let some = SomeClass(sem: s) + weakSome = some + let tsv = ThreadSpecificVariable() + tsv.currentValue = some + XCTAssertNotNil(tsv.currentValue) + } + s.wait() + XCTAssertNil(weakSome) + } + + func testThreadSpecificDoesNotLeakIfThreadExitsAfterUnset() throws { + let s = DispatchSemaphore(value: 0) + class SomeClass { + let s: DispatchSemaphore + init(sem: DispatchSemaphore) { self.s = sem } + deinit { + s.signal() + } + } + weak var weakSome: SomeClass? = nil + Thread.spawnAndRun { _ in + let some = SomeClass(sem: s) + weakSome = some + let tsv = ThreadSpecificVariable() + tsv.currentValue = some + XCTAssertNotNil(tsv.currentValue) + tsv.currentValue = nil + } + s.wait() + XCTAssertNil(weakSome) + } + + func testThreadSpecificDoesNotLeakIfReplacedWithNewValue() throws { + let s1 = DispatchSemaphore(value: 0) + let s2 = DispatchSemaphore(value: 0) + let s3 = DispatchSemaphore(value: 0) + class SomeClass { + let s: DispatchSemaphore + init(sem: DispatchSemaphore) { self.s = sem } + deinit { + s.signal() + } + } + weak var weakSome1: SomeClass? = nil + weak var weakSome2: SomeClass? = nil + weak var weakSome3: SomeClass? = nil + Thread.spawnAndRun { _ in + let some1 = SomeClass(sem: s1) + weakSome1 = some1 + let some2 = SomeClass(sem: s2) + weakSome2 = some2 + let some3 = SomeClass(sem: s3) + weakSome3 = some3 + + let tsv = ThreadSpecificVariable() + tsv.currentValue = some1 + XCTAssertNotNil(tsv.currentValue) + tsv.currentValue = some2 + XCTAssertNotNil(tsv.currentValue) + tsv.currentValue = some3 + XCTAssertNotNil(tsv.currentValue) + } + s1.wait() + s2.wait() + s3.wait() + XCTAssertNil(weakSome1) + XCTAssertNil(weakSome2) + XCTAssertNil(weakSome3) + } + + func testSharingThreadSpecificVariableWorks() throws { + let s = DispatchSemaphore(value: 0) + class SomeClass { + let s: DispatchSemaphore + init(sem: DispatchSemaphore) { self.s = sem } + deinit { + s.signal() + } + } + weak var weakSome: SomeClass? = nil + Thread.spawnAndRun { _ in + let some = SomeClass(sem: s) + weakSome = some + let tsv = ThreadSpecificVariable() + for _ in 0..<10 { + Thread.spawnAndRun { _ in + tsv.currentValue = some + } + } + } + s.wait() + XCTAssertNil(weakSome) + } + + func testThreadSpecificInitWithValueWorks() throws { + class SomeClass {} + let tsv = ThreadSpecificVariable(value: SomeClass()) + XCTAssertNotNil(tsv.currentValue) + } +}