implement thread specific values

This commit is contained in:
Johannes Weiß committed 2018-02-08 17:37:01 +00:00
1 parent 9b0b0f9b51
commit ebf351abda
4 files changed
+289

No files matched your search

+53
View File
@@ -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<T: AnyObject> {
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<AnyObject>.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<T>.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<T>.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
+1
View File
@@ -64,6 +64,7 @@ import XCTest
testCase(SocketChannelTest.allTests),
testCase(NIOConcurrencyHelpersTests.allTests),
testCase(SystemTest.allTests),
testCase(ThreadTest.allTests),
testCase(TypeAssistedChannelHandlerTest.allTests),
testCase(UtilitiesTest.allTests),
])
+42
View File
@@ -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),
]
}
}
+193
View File
@@ -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<SomeClass> = ThreadSpecificVariable()
XCTAssertNil(tsv.currentValue)
s.signal()
}
s.wait()
}
func testThreadSpecificsWorks() throws {
class SomeClass {}
let s = DispatchSemaphore(value: 0)
Thread.spawnAndRun { _ in
let tsv: ThreadSpecificVariable<SomeClass> = 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<SomeClass>()
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<SomeClass>()
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<SomeClass>()
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<SomeClass>()
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<SomeClass>()
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)
}
}