mirror of
https://github.com/apple/swift-nio
synced 2026-11-29 05:24:21 +00:00
Use NIOThreadPool in NIOFileSystem (#2692)
Motivation: There are two thread pools: one in NIOFileSystem and one in NIOPosix; we should avoid the duplication. Modifications: - Switch to using NIOThreadPool - Remove the old thread pool and associated code - Add an init to FileSystem which takes a thread pool Result: Less duplication
This commit is contained in:
1 parent
6b29fc3c2b
commit
2d840c586f
11 files changed
+145
-1054
No files matched your search
@@ -1,423 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2023 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(tvOS) || os(watchOS) || os(Linux) || os(Android)
|
||||
import Atomics
|
||||
import DequeModule
|
||||
import Dispatch
|
||||
import NIOConcurrencyHelpers
|
||||
|
||||
@_spi(Testing)
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public final class IOExecutor: Sendable {
|
||||
/// Used to generate IDs for work items. Don't use directly,
|
||||
/// use ``generateWorkID()`` instead.
|
||||
private let workID = ManagedAtomic(UInt64(0))
|
||||
/// The workers.
|
||||
private let workers: [Worker]
|
||||
|
||||
/// Generates a unique ID for a work item. This is used to identify the work
|
||||
/// for cancellation.
|
||||
private func generateWorkID() -> UInt64 {
|
||||
// We only require uniqueness: relaxed is sufficient.
|
||||
return self.workID.loadThenWrappingIncrement(ordering: .relaxed)
|
||||
}
|
||||
|
||||
/// Create a running executor with the given number of threads.
|
||||
///
|
||||
/// - Precondition: `numberOfThreads` must be greater than zero.
|
||||
/// - Returns: a running executor which does work on `numberOfThreads` threads.
|
||||
@_spi(Testing)
|
||||
public static func running(numberOfThreads: Int) async -> IOExecutor {
|
||||
let executor = IOExecutor(numberOfThreads: numberOfThreads)
|
||||
await executor.start()
|
||||
return executor
|
||||
}
|
||||
|
||||
/// Create a running executor with the given number of threads.
|
||||
///
|
||||
/// - Precondition: `numberOfThreads` must be greater than zero.
|
||||
/// - Returns: a running executor which does work on `numberOfThreads` threads.
|
||||
@_spi(Testing)
|
||||
public static func runningAsync(numberOfThreads: Int) -> IOExecutor {
|
||||
let executor = IOExecutor(numberOfThreads: numberOfThreads)
|
||||
Task { await executor.start() }
|
||||
return executor
|
||||
}
|
||||
|
||||
private init(numberOfThreads: Int) {
|
||||
precondition(numberOfThreads > 0, "numberOfThreads must be greater than zero")
|
||||
var workers = [Worker]()
|
||||
workers.reserveCapacity(numberOfThreads)
|
||||
for _ in 0..<numberOfThreads {
|
||||
workers.append(Worker())
|
||||
}
|
||||
self.workers = workers
|
||||
}
|
||||
|
||||
private func start() async {
|
||||
await withTaskGroup(of: Void.self) { group in
|
||||
for (index, worker) in self.workers.enumerated() {
|
||||
group.addTask {
|
||||
await worker.start(name: "io-worker-\(index)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes work on a thread owned by the executor and returns its result.
|
||||
///
|
||||
/// - Parameter work: A closure to execute.
|
||||
/// - Returns: The result of the closure.
|
||||
@_spi(Testing)
|
||||
public func execute<R: Sendable>(
|
||||
_ work: @Sendable @escaping () throws -> R
|
||||
) async throws -> R {
|
||||
let workerIndex = self.pickWorker()
|
||||
let workID = self.generateWorkID()
|
||||
|
||||
return try await withTaskCancellationHandler {
|
||||
return try await withUnsafeThrowingContinuation { continuation in
|
||||
self.workers[workerIndex].enqueue(id: workID) { action in
|
||||
switch action {
|
||||
case .run:
|
||||
continuation.resume(with: Result(catching: work))
|
||||
case .cancel:
|
||||
continuation.resume(throwing: CancellationError())
|
||||
case .reject:
|
||||
let error = FileSystemError(
|
||||
code: .unavailable,
|
||||
message: "The executor has been shutdown.",
|
||||
cause: nil,
|
||||
location: .here()
|
||||
)
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
} onCancel: {
|
||||
self.workers[workerIndex].cancel(workID: workID)
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes work on a thread owned by the executor and notifies a completion
|
||||
/// handler with the result.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - work: A closure to execute.
|
||||
/// - onCompletion: A closure to notify with the result of the work.
|
||||
@_spi(Testing)
|
||||
public func execute<R>(
|
||||
work: @Sendable @escaping () throws -> R,
|
||||
onCompletion: @Sendable @escaping (Result<R, Error>) -> Void
|
||||
) {
|
||||
let workerIndex = self.pickWorker()
|
||||
let workID = self.generateWorkID()
|
||||
self.workers[workerIndex].enqueue(id: workID) { action in
|
||||
switch action {
|
||||
case .run:
|
||||
onCompletion(Result(catching: work))
|
||||
case .cancel:
|
||||
onCompletion(.failure(CancellationError()))
|
||||
case .reject:
|
||||
let error = FileSystemError(
|
||||
code: .unavailable,
|
||||
message: "The executor has been shutdown.",
|
||||
cause: nil,
|
||||
location: .here()
|
||||
)
|
||||
onCompletion(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop accepting new tasks and wait for all enqueued work to finish.
|
||||
///
|
||||
/// Any work submitted to the executor whilst it is draining or once it
|
||||
/// has finished draining will not be executed.
|
||||
@_spi(Testing)
|
||||
public func drain() async {
|
||||
await withTaskGroup(of: Void.self) { group in
|
||||
for worker in self.workers {
|
||||
group.addTask {
|
||||
await worker.stop()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the index of the work to submit the next item of work on.
|
||||
///
|
||||
/// If there are more than two workers then the "power of two random choices"
|
||||
/// approach (https://www.eecs.harvard.edu/~michaelm/postscripts/tpds2001.pdf) is
|
||||
/// used whereby two workers are selected at random and the one with the least
|
||||
/// amount of work is chosen.
|
||||
///
|
||||
/// If there are one or two workers then the one with the least work is
|
||||
/// chosen.
|
||||
private func pickWorker() -> Int {
|
||||
// 'numberOfThreads' is guaranteed to be > 0.
|
||||
switch self.workers.count {
|
||||
case 1:
|
||||
return 0
|
||||
case 2:
|
||||
return self.indexOfLeastBusyWorkerAtIndices(0, 1)
|
||||
default:
|
||||
// For more than two threads use the 'power of two random choices'.
|
||||
let i = self.workers.indices.randomElement()!
|
||||
let j = self.workers.indices.randomElement()!
|
||||
|
||||
if i == j {
|
||||
return i
|
||||
} else {
|
||||
return self.indexOfLeastBusyWorkerAtIndices(i, j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func indexOfLeastBusyWorkerAtIndices(_ i: Int, _ j: Int) -> Int {
|
||||
let workOnI = self.workers[i].numberOfQueuedTasks
|
||||
let workOnJ = self.workers[j].numberOfQueuedTasks
|
||||
return workOnI < workOnJ ? i : j
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension IOExecutor {
|
||||
final class Worker: @unchecked Sendable {
|
||||
/// An item of work executed by the worker.
|
||||
typealias WorkItem = @Sendable (WorkAction) -> Void
|
||||
|
||||
/// Whether the work should be executed or cancelled.
|
||||
enum WorkAction {
|
||||
case run
|
||||
case cancel
|
||||
case reject
|
||||
}
|
||||
|
||||
/// The state of the worker.
|
||||
private enum State {
|
||||
case notStarted
|
||||
case starting(CheckedContinuation<Void, Never>)
|
||||
case active(Thread)
|
||||
case draining(CheckedContinuation<Void, Never>)
|
||||
case stopped
|
||||
|
||||
mutating func starting(continuation: CheckedContinuation<Void, Never>) {
|
||||
switch self {
|
||||
case .notStarted:
|
||||
self = .starting(continuation)
|
||||
case .active, .starting, .draining, .stopped:
|
||||
fatalError("\(#function) while worker was active/starting/draining/stopped")
|
||||
}
|
||||
}
|
||||
|
||||
mutating func activate(_ thread: Thread) -> CheckedContinuation<Void, Never> {
|
||||
switch self {
|
||||
case let .starting(continuation):
|
||||
self = .active(thread)
|
||||
return continuation
|
||||
case .notStarted, .active, .draining, .stopped:
|
||||
fatalError("\(#function) while worker was notStarted/active/draining/stopped")
|
||||
}
|
||||
}
|
||||
|
||||
mutating func drained() -> CheckedContinuation<Void, Never> {
|
||||
switch self {
|
||||
case let .draining(continuation):
|
||||
self = .stopped
|
||||
return continuation
|
||||
case .notStarted, .starting, .active, .stopped:
|
||||
fatalError("\(#function) while worker was notStarted/starting/active/stopped")
|
||||
}
|
||||
}
|
||||
|
||||
var isStopped: Bool {
|
||||
switch self {
|
||||
case .stopped:
|
||||
return true
|
||||
case .notStarted, .starting, .active, .draining:
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let lock = NIOLock()
|
||||
private var state: State
|
||||
/// Items of work waiting to be executed and their ID.
|
||||
private var workQueue: Deque<(UInt64, WorkItem)>
|
||||
/// IDs of work items which have been marked as cancelled but not yet
|
||||
/// processed.
|
||||
private var cancelledTasks: [UInt64]
|
||||
// TODO: make checking for cancellation cheaper by maintaining a heap of cancelled
|
||||
// IDs and ensuring work is in order of increasing ID. With that we can check the ID
|
||||
// of the popped work item against the top of the heap.
|
||||
|
||||
/// Signalled when an item of work is added to the work queue.
|
||||
private let semaphore: DispatchSemaphore
|
||||
/// The number of items in the work queue. This is used by the executor to
|
||||
/// make decisions on where to enqueue work so relaxed memory ordering is fine.
|
||||
private let queuedWork = ManagedAtomic(0)
|
||||
|
||||
internal init() {
|
||||
self.state = .notStarted
|
||||
self.semaphore = DispatchSemaphore(value: 0)
|
||||
self.workQueue = []
|
||||
self.cancelledTasks = []
|
||||
}
|
||||
|
||||
deinit {
|
||||
assert(self.state.isStopped, "The IOExecutor MUST be shutdown before deinit")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension IOExecutor.Worker {
|
||||
func start(name: String) async {
|
||||
self.lock.lock()
|
||||
await withCheckedContinuation { continuation in
|
||||
self.state.starting(continuation: continuation)
|
||||
self.lock.unlock()
|
||||
|
||||
Thread.spawnAndRun(name: name, detachThread: false) { thread in
|
||||
let continuation = self.lock.withLock { self.state.activate(thread) }
|
||||
continuation.resume()
|
||||
self.process()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var numberOfQueuedTasks: Int {
|
||||
return self.queuedWork.load(ordering: .relaxed)
|
||||
}
|
||||
|
||||
func enqueue(id: UInt64, _ item: @escaping WorkItem) {
|
||||
let didEnqueue = self.lock.withLock {
|
||||
self._enqueue(id: id, item)
|
||||
}
|
||||
|
||||
if didEnqueue {
|
||||
self.queuedWork.wrappingIncrement(ordering: .relaxed)
|
||||
self.semaphore.signal()
|
||||
} else {
|
||||
// Draining or stopped.
|
||||
item(.reject)
|
||||
}
|
||||
}
|
||||
|
||||
private func _enqueue(id: UInt64, _ item: @escaping WorkItem) -> Bool {
|
||||
switch self.state {
|
||||
case .notStarted, .starting, .active:
|
||||
self.workQueue.append((id, item))
|
||||
return true
|
||||
case .draining, .stopped:
|
||||
// New work is rejected in these states.
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func cancel(workID: UInt64) {
|
||||
self.lock.withLock {
|
||||
// The work will be cancelled when pulled from the work queue. This means
|
||||
// there's a delay before the work is actually cancelled; we trade that off
|
||||
// against the cost of scanning the work queue for an item to cancel and then
|
||||
// removing it which is O(n) (which could be O(n^2) for bulk cancellation).
|
||||
self.cancelledTasks.append(workID)
|
||||
}
|
||||
}
|
||||
|
||||
func stop() async {
|
||||
self.lock.lock()
|
||||
switch self.state {
|
||||
case .notStarted:
|
||||
self.state = .stopped
|
||||
while let work = self.workQueue.popFirst() {
|
||||
work.1(.reject)
|
||||
}
|
||||
|
||||
case let .active(thread):
|
||||
await withCheckedContinuation { continuation in
|
||||
self.state = .draining(continuation)
|
||||
self.lock.unlock()
|
||||
|
||||
// Signal the semaphore: 'process()' waits on the semaphore for work so
|
||||
// always expects the queue to be non-empty. This is the exception that
|
||||
// indicates to 'process()' that it can stop.
|
||||
self.semaphore.signal()
|
||||
}
|
||||
precondition(self.lock.withLock({ self.state.isStopped }))
|
||||
// This won't block, we just drained the work queue so 'self.process()' will have
|
||||
// returned
|
||||
thread.join()
|
||||
|
||||
case .starting, .draining:
|
||||
fatalError("Worker is already starting/draining")
|
||||
|
||||
case .stopped:
|
||||
self.lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
private func process() {
|
||||
enum Instruction {
|
||||
case run(WorkItem)
|
||||
case cancel(WorkItem)
|
||||
case stopWorking(CheckedContinuation<Void, Never>)
|
||||
}
|
||||
|
||||
while true {
|
||||
// Wait for work to be signalled via the semaphore. It is signalled for every time an
|
||||
// item of work is added to the queue. It is signalled an additional time when the worker
|
||||
// is shutting down: in that case there is no corresponding work item in the queue so
|
||||
// 'popFirst()' will return 'nil'; that's the signal to stop looping.
|
||||
self.semaphore.wait()
|
||||
|
||||
let instruction: Instruction = self.lock.withLock {
|
||||
switch self.state {
|
||||
case let .draining(continuation):
|
||||
if self.workQueue.isEmpty {
|
||||
self.state = .stopped
|
||||
return .stopWorking(continuation)
|
||||
}
|
||||
// There's still work to do: continue as if active.
|
||||
fallthrough
|
||||
|
||||
case .active:
|
||||
let (id, work) = self.workQueue.removeFirst()
|
||||
if let index = self.cancelledTasks.firstIndex(of: id) {
|
||||
self.cancelledTasks.remove(at: index)
|
||||
return .cancel(work)
|
||||
} else {
|
||||
return .run(work)
|
||||
}
|
||||
|
||||
case .notStarted, .starting, .stopped:
|
||||
fatalError("Impossible state")
|
||||
}
|
||||
}
|
||||
|
||||
switch instruction {
|
||||
case let .run(work):
|
||||
work(.run)
|
||||
case let .cancel(work):
|
||||
work(.cancel)
|
||||
case let .stopWorking(continuation):
|
||||
continuation.resume()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,99 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2023 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(tvOS) || os(watchOS) || os(Linux) || os(Android)
|
||||
#if os(Linux) || os(FreeBSD) || os(Android)
|
||||
import CNIOLinux
|
||||
#endif
|
||||
|
||||
protocol ThreadOps {
|
||||
associatedtype ThreadHandle
|
||||
associatedtype ThreadSpecificKey
|
||||
associatedtype ThreadSpecificKeyDestructor
|
||||
|
||||
static func run(
|
||||
handle: inout ThreadHandle?,
|
||||
args: Ref<Thread.ThreadBoxValue>,
|
||||
detachThread: Bool
|
||||
)
|
||||
static func joinThread(_ thread: ThreadHandle)
|
||||
static func threadName(_ thread: ThreadHandle) -> String?
|
||||
static func compareThreads(_ lhs: ThreadHandle, _ rhs: ThreadHandle) -> Bool
|
||||
}
|
||||
|
||||
/// A Thread that executes some runnable block.
|
||||
///
|
||||
/// All methods exposed are thread-safe.
|
||||
final class Thread {
|
||||
internal typealias ThreadBoxValue = (body: (Thread) -> Void, name: String?)
|
||||
internal typealias ThreadBox = Ref<ThreadBoxValue>
|
||||
|
||||
private let desiredName: String?
|
||||
|
||||
/// The thread handle used by this instance.
|
||||
private let handle: ThreadOpsSystem.ThreadHandle
|
||||
|
||||
/// Create a new instance
|
||||
///
|
||||
/// - arguments:
|
||||
/// - handle: The `ThreadOpsSystem.ThreadHandle` that is wrapped and used by the `Thread`.
|
||||
internal init(handle: ThreadOpsSystem.ThreadHandle, desiredName: String?) {
|
||||
self.handle = handle
|
||||
self.desiredName = desiredName
|
||||
}
|
||||
|
||||
/// Execute the given body with the `pthread_t` that is used by this `Thread` as argument.
|
||||
///
|
||||
/// - warning: Do not escape `pthread_t` from the closure for later use.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - body: The closure that will accept the `pthread_t`.
|
||||
/// - returns: The value returned by `body`.
|
||||
internal func withUnsafeThreadHandle<T>(
|
||||
_ body: (ThreadOpsSystem.ThreadHandle) throws -> T
|
||||
) rethrows -> T {
|
||||
return try body(self.handle)
|
||||
}
|
||||
|
||||
/// Get current name of the `Thread` or `nil` if not set.
|
||||
var currentName: String? {
|
||||
return ThreadOpsSystem.threadName(self.handle)
|
||||
}
|
||||
|
||||
func join() {
|
||||
ThreadOpsSystem.joinThread(self.handle)
|
||||
}
|
||||
|
||||
/// Spawns and runs some task in a `Thread`.
|
||||
///
|
||||
/// - arguments:
|
||||
/// - name: The name of the `Thread` or `nil` if no specific name should be set.
|
||||
/// - body: The function to execute within the spawned `Thread`.
|
||||
/// - detach: Whether to detach the thread. If the thread is not detached it must be `join`ed.
|
||||
static func spawnAndRun(
|
||||
name: String? = nil,
|
||||
detachThread: Bool = true,
|
||||
body: @escaping (Thread) -> Void
|
||||
) {
|
||||
var handle: ThreadOpsSystem.ThreadHandle? = nil
|
||||
|
||||
// Store everything we want to pass into the c function in a Box so we
|
||||
// can hand-over the reference.
|
||||
let tuple: ThreadBoxValue = (body: body, name: name)
|
||||
let box = ThreadBox(tuple)
|
||||
|
||||
ThreadOpsSystem.run(handle: &handle, args: box, detachThread: detachThread)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,156 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2023 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(tvOS) || os(watchOS) || os(Linux) || os(Android)
|
||||
#if canImport(Glibc) || canImport(Musl)
|
||||
import CNIOLinux
|
||||
|
||||
private let sys_pthread_getname_np = CNIOLinux_pthread_getname_np
|
||||
private let sys_pthread_setname_np = CNIOLinux_pthread_setname_np
|
||||
#if os(Android)
|
||||
private typealias ThreadDestructor = @convention(c) (UnsafeMutableRawPointer) ->
|
||||
UnsafeMutableRawPointer
|
||||
#else
|
||||
private typealias ThreadDestructor = @convention(c) (UnsafeMutableRawPointer?) ->
|
||||
UnsafeMutableRawPointer?
|
||||
#endif
|
||||
#elseif canImport(Darwin)
|
||||
import Darwin
|
||||
|
||||
private let sys_pthread_getname_np = pthread_getname_np
|
||||
// Emulate the same method signature as pthread_setname_np on Linux.
|
||||
private func sys_pthread_setname_np(_ p: pthread_t, _ pointer: UnsafePointer<Int8>) -> Int32 {
|
||||
assert(pthread_equal(pthread_self(), p) != 0)
|
||||
pthread_setname_np(pointer)
|
||||
// Will never fail on macOS so just return 0 which will be used on linux to signal it not failed.
|
||||
return 0
|
||||
}
|
||||
private typealias ThreadDestructor = @convention(c) (UnsafeMutableRawPointer) ->
|
||||
UnsafeMutableRawPointer?
|
||||
#endif
|
||||
|
||||
private func sysPthread_create(
|
||||
handle: UnsafeMutablePointer<pthread_t?>,
|
||||
destructor: @escaping ThreadDestructor,
|
||||
args: UnsafeMutableRawPointer?
|
||||
) -> CInt {
|
||||
#if canImport(Darwin)
|
||||
return pthread_create(handle, nil, destructor, args)
|
||||
#elseif canImport(Glibc) || canImport(Musl)
|
||||
#if canImport(Glibc)
|
||||
var handleLinux = pthread_t()
|
||||
#else
|
||||
var handleLinux = pthread_t(bitPattern: 0)
|
||||
#endif
|
||||
let result = pthread_create(
|
||||
&handleLinux,
|
||||
nil,
|
||||
destructor,
|
||||
args
|
||||
)
|
||||
handle.pointee = handleLinux
|
||||
return result
|
||||
#endif
|
||||
}
|
||||
|
||||
typealias ThreadOpsSystem = ThreadOpsPosix
|
||||
|
||||
enum ThreadOpsPosix: ThreadOps {
|
||||
typealias ThreadHandle = pthread_t
|
||||
typealias ThreadSpecificKey = pthread_key_t
|
||||
#if canImport(Darwin)
|
||||
typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer) -> Void
|
||||
#elseif canImport(Glibc) || canImport(Musl)
|
||||
typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer?) -> Void
|
||||
#endif
|
||||
|
||||
static func threadName(_ thread: ThreadOpsSystem.ThreadHandle) -> String? {
|
||||
// 64 bytes should be good enough as on Linux the limit is usually 16
|
||||
// and it's very unlikely a user will ever set something longer
|
||||
// anyway.
|
||||
var chars: [CChar] = Array(repeating: 0, count: 64)
|
||||
return chars.withUnsafeMutableBufferPointer { ptr in
|
||||
guard sys_pthread_getname_np(thread, ptr.baseAddress!, ptr.count) == 0 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let buffer: UnsafeRawBufferPointer =
|
||||
UnsafeRawBufferPointer(UnsafeBufferPointer<CChar>(rebasing: ptr.prefix { $0 != 0 }))
|
||||
return String(decoding: buffer, as: Unicode.UTF8.self)
|
||||
}
|
||||
}
|
||||
|
||||
static func run(
|
||||
handle: inout ThreadOpsSystem.ThreadHandle?,
|
||||
args: Ref<Thread.ThreadBoxValue>,
|
||||
detachThread: Bool
|
||||
) {
|
||||
let argv0 = Unmanaged.passRetained(args).toOpaque()
|
||||
let res = sysPthread_create(
|
||||
handle: &handle,
|
||||
destructor: {
|
||||
// Cast to UnsafeMutableRawPointer? and force unwrap to make the
|
||||
// same code work on macOS and Linux.
|
||||
let boxed = Unmanaged<Thread.ThreadBox>
|
||||
.fromOpaque(($0 as UnsafeMutableRawPointer?)!)
|
||||
.takeRetainedValue()
|
||||
let (body, name) = (boxed.value.body, boxed.value.name)
|
||||
let hThread: ThreadOpsSystem.ThreadHandle = pthread_self()
|
||||
|
||||
if let name = name {
|
||||
let maximumThreadNameLength: Int
|
||||
#if canImport(Glibc) || canImport(Musl)
|
||||
maximumThreadNameLength = 15
|
||||
#elseif canImport(Darwin)
|
||||
maximumThreadNameLength = .max
|
||||
#endif
|
||||
name.prefix(maximumThreadNameLength).withCString { namePtr in
|
||||
// this is non-critical so we ignore the result here, we've seen
|
||||
// EPERM in containers.
|
||||
_ = sys_pthread_setname_np(hThread, namePtr)
|
||||
}
|
||||
}
|
||||
|
||||
body(Thread(handle: hThread, desiredName: name))
|
||||
|
||||
#if os(Android)
|
||||
return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)!
|
||||
#else
|
||||
return nil
|
||||
#endif
|
||||
},
|
||||
args: argv0
|
||||
)
|
||||
precondition(res == 0, "Unable to create thread: \(res)")
|
||||
|
||||
if detachThread {
|
||||
let detachError = pthread_detach(handle!)
|
||||
precondition(detachError == 0, "pthread_detach failed with error \(detachError)")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static func joinThread(_ thread: ThreadOpsSystem.ThreadHandle) {
|
||||
let err = pthread_join(thread, nil)
|
||||
assert(err == 0, "pthread_join failed with \(err)")
|
||||
}
|
||||
|
||||
static func compareThreads(
|
||||
_ lhs: ThreadOpsSystem.ThreadHandle,
|
||||
_ rhs: ThreadOpsSystem.ThreadHandle
|
||||
) -> Bool {
|
||||
return pthread_equal(lhs, rhs) != 0
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -15,6 +15,7 @@
|
||||
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android)
|
||||
import NIOConcurrencyHelpers
|
||||
import NIOCore
|
||||
import NIOPosix
|
||||
@preconcurrency import SystemPackage
|
||||
|
||||
#if canImport(Darwin)
|
||||
@@ -31,7 +32,7 @@ import Musl
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public final class SystemFileHandle {
|
||||
/// The executor on which to execute system calls.
|
||||
internal var executor: IOExecutor { self.sendableView.executor }
|
||||
internal var threadPool: NIOThreadPool { self.sendableView.threadPool }
|
||||
|
||||
/// The path used to open this handle.
|
||||
internal var path: FilePath { self.sendableView.path }
|
||||
@@ -77,7 +78,7 @@ public final class SystemFileHandle {
|
||||
fileprivate let lifecycle: NIOLockedValueBox<Lifecycle>
|
||||
|
||||
/// The executor on which to execute system calls.
|
||||
internal let executor: IOExecutor
|
||||
internal let threadPool: NIOThreadPool
|
||||
|
||||
/// The path used to open this handle.
|
||||
internal let path: FilePath
|
||||
@@ -87,12 +88,12 @@ public final class SystemFileHandle {
|
||||
|
||||
fileprivate init(
|
||||
lifecycle: Lifecycle,
|
||||
executor: IOExecutor,
|
||||
threadPool: NIOThreadPool,
|
||||
path: FilePath,
|
||||
materialization: Materialization?
|
||||
) {
|
||||
self.lifecycle = NIOLockedValueBox(lifecycle)
|
||||
self.executor = executor
|
||||
self.threadPool = threadPool
|
||||
self.path = path
|
||||
self.materialization = materialization
|
||||
}
|
||||
@@ -110,11 +111,11 @@ public final class SystemFileHandle {
|
||||
takingOwnershipOf descriptor: FileDescriptor,
|
||||
path: FilePath,
|
||||
materialization: Materialization? = nil,
|
||||
executor: IOExecutor
|
||||
threadPool: NIOThreadPool
|
||||
) {
|
||||
self.sendableView = SendableView(
|
||||
lifecycle: .open(descriptor),
|
||||
executor: executor,
|
||||
threadPool: threadPool,
|
||||
path: path,
|
||||
materialization: materialization
|
||||
)
|
||||
@@ -193,37 +194,37 @@ extension SystemFileHandle: FileHandleProtocol {
|
||||
// currently using.
|
||||
|
||||
public func info() async throws -> FileInfo {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._info().get()
|
||||
}
|
||||
}
|
||||
|
||||
public func replacePermissions(_ permissions: FilePermissions) async throws {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._replacePermissions(permissions)
|
||||
}
|
||||
}
|
||||
|
||||
public func addPermissions(_ permissions: FilePermissions) async throws -> FilePermissions {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._addPermissions(permissions)
|
||||
}
|
||||
}
|
||||
|
||||
public func removePermissions(_ permissions: FilePermissions) async throws -> FilePermissions {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._removePermissions(permissions)
|
||||
}
|
||||
}
|
||||
|
||||
public func attributeNames() async throws -> [String] {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._attributeNames()
|
||||
}
|
||||
}
|
||||
|
||||
public func valueForAttribute(_ name: String) async throws -> [UInt8] {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._valueForAttribute(name)
|
||||
}
|
||||
}
|
||||
@@ -232,19 +233,19 @@ extension SystemFileHandle: FileHandleProtocol {
|
||||
_ bytes: some (Sendable & RandomAccessCollection<UInt8>),
|
||||
attribute name: String
|
||||
) async throws {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._updateValueForAttribute(bytes, attribute: name)
|
||||
}
|
||||
}
|
||||
|
||||
public func removeValueForAttribute(_ name: String) async throws {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._removeValueForAttribute(name)
|
||||
}
|
||||
}
|
||||
|
||||
public func synchronize() async throws {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._synchronize()
|
||||
}
|
||||
}
|
||||
@@ -252,7 +253,7 @@ extension SystemFileHandle: FileHandleProtocol {
|
||||
public func withUnsafeDescriptor<R: Sendable>(
|
||||
_ execute: @Sendable @escaping (FileDescriptor) throws -> R
|
||||
) async throws -> R {
|
||||
try await self.executor.execute { [sendableView] in
|
||||
try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._withUnsafeDescriptor {
|
||||
return try execute($0)
|
||||
} onUnavailable: {
|
||||
@@ -343,13 +344,13 @@ extension SystemFileHandle: FileHandleProtocol {
|
||||
}
|
||||
|
||||
public func close() async throws {
|
||||
try await self.executor.execute { [sendableView] in
|
||||
try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._close(materialize: true).get()
|
||||
}
|
||||
}
|
||||
|
||||
public func close(makeChangesVisible: Bool) async throws {
|
||||
try await self.executor.execute { [sendableView] in
|
||||
try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._close(materialize: makeChangesVisible).get()
|
||||
}
|
||||
}
|
||||
@@ -864,7 +865,7 @@ extension SystemFileHandle: ReadableFileHandleProtocol {
|
||||
fromAbsoluteOffset offset: Int64,
|
||||
length: ByteCount
|
||||
) async throws -> ByteBuffer {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
return try sendableView._withUnsafeDescriptor { descriptor in
|
||||
try descriptor.readChunk(
|
||||
fromAbsoluteOffset: offset,
|
||||
@@ -930,7 +931,7 @@ extension SystemFileHandle: WritableFileHandleProtocol {
|
||||
contentsOf bytes: some (Sequence<UInt8> & Sendable),
|
||||
toAbsoluteOffset offset: Int64
|
||||
) async throws -> Int64 {
|
||||
return try await self.executor.execute { [sendableView] in
|
||||
return try await self.threadPool.runIfActive { [sendableView] in
|
||||
return try sendableView._withUnsafeDescriptor { descriptor in
|
||||
try descriptor.write(contentsOf: bytes, toAbsoluteOffset: offset)
|
||||
.flatMapError { error in
|
||||
@@ -979,7 +980,7 @@ extension SystemFileHandle: WritableFileHandleProtocol {
|
||||
}
|
||||
|
||||
public func resize(to size: ByteCount) async throws {
|
||||
try await self.executor.execute { [sendableView] in
|
||||
try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._resize(to: size).get()
|
||||
}
|
||||
}
|
||||
@@ -1022,7 +1023,7 @@ extension SystemFileHandle: DirectoryFileHandleProtocol {
|
||||
options: OpenOptions.Read
|
||||
) async throws -> SystemFileHandle {
|
||||
let opts = options.descriptorOptions.union(.nonBlocking)
|
||||
let handle = try await self.executor.execute { [sendableView] in
|
||||
let handle = try await self.threadPool.runIfActive { [sendableView] in
|
||||
let handle = try sendableView._open(
|
||||
atPath: path,
|
||||
mode: .readOnly,
|
||||
@@ -1041,7 +1042,7 @@ extension SystemFileHandle: DirectoryFileHandleProtocol {
|
||||
) async throws -> SystemFileHandle {
|
||||
let perms = options.permissionsForRegularFile
|
||||
let opts = options.descriptorOptions.union(.nonBlocking)
|
||||
let handle = try await self.executor.execute { [sendableView] in
|
||||
let handle = try await self.threadPool.runIfActive { [sendableView] in
|
||||
let handle = try sendableView._open(
|
||||
atPath: path,
|
||||
mode: .readWrite,
|
||||
@@ -1061,7 +1062,7 @@ extension SystemFileHandle: DirectoryFileHandleProtocol {
|
||||
) async throws -> SystemFileHandle {
|
||||
let perms = options.permissionsForRegularFile
|
||||
let opts = options.descriptorOptions.union(.nonBlocking)
|
||||
let handle = try await self.executor.execute { [sendableView] in
|
||||
let handle = try await self.threadPool.runIfActive { [sendableView] in
|
||||
let handle = try sendableView._open(
|
||||
atPath: path,
|
||||
mode: .writeOnly,
|
||||
@@ -1080,7 +1081,7 @@ extension SystemFileHandle: DirectoryFileHandleProtocol {
|
||||
options: OpenOptions.Directory
|
||||
) async throws -> SystemFileHandle {
|
||||
let opts = options.descriptorOptions.union(.nonBlocking)
|
||||
let handle = try await self.executor.execute { [sendableView] in
|
||||
let handle = try await self.threadPool.runIfActive { [sendableView] in
|
||||
let handle = try sendableView._open(
|
||||
atPath: path,
|
||||
mode: .readOnly,
|
||||
@@ -1112,7 +1113,7 @@ extension SystemFileHandle.SendableView {
|
||||
options: options,
|
||||
permissions: permissions,
|
||||
transactionalIfPossible: transactional,
|
||||
executor: self.executor
|
||||
threadPool: self.threadPool
|
||||
)
|
||||
} else if self.path.isAbsolute {
|
||||
// The parent path is absolute and the provided path is relative; combine them.
|
||||
@@ -1122,7 +1123,7 @@ extension SystemFileHandle.SendableView {
|
||||
options: options,
|
||||
permissions: permissions,
|
||||
transactionalIfPossible: transactional,
|
||||
executor: self.executor
|
||||
threadPool: self.threadPool
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1143,7 +1144,7 @@ extension SystemFileHandle.SendableView {
|
||||
SystemFileHandle(
|
||||
takingOwnershipOf: newDescriptor,
|
||||
path: self.path.appending(path.components).lexicallyNormalized(),
|
||||
executor: self.executor
|
||||
threadPool: self.threadPool
|
||||
)
|
||||
}.mapError { errno in
|
||||
.open("openat", error: errno, path: self.path, location: .here())
|
||||
@@ -1170,7 +1171,7 @@ extension SystemFileHandle {
|
||||
options: FileDescriptor.OpenOptions,
|
||||
permissions: FilePermissions?,
|
||||
transactionalIfPossible transactional: Bool,
|
||||
executor: IOExecutor
|
||||
threadPool: NIOThreadPool
|
||||
) -> Result<SystemFileHandle, FileSystemError> {
|
||||
let isWritable = (mode == .writeOnly || mode == .readWrite)
|
||||
let exclusiveCreate = options.contains(.exclusiveCreate)
|
||||
@@ -1194,7 +1195,7 @@ extension SystemFileHandle {
|
||||
mode: mode,
|
||||
options: options,
|
||||
permissions: permissions,
|
||||
executor: executor,
|
||||
threadPool: threadPool,
|
||||
useTemporaryFileIfPossible: temporaryHardLink
|
||||
)
|
||||
} else {
|
||||
@@ -1203,7 +1204,7 @@ extension SystemFileHandle {
|
||||
mode: mode,
|
||||
options: options,
|
||||
permissions: permissions,
|
||||
executor: executor
|
||||
threadPool: threadPool
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1213,7 +1214,7 @@ extension SystemFileHandle {
|
||||
mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions,
|
||||
permissions: FilePermissions?,
|
||||
executor: IOExecutor
|
||||
threadPool: NIOThreadPool
|
||||
) -> Result<SystemFileHandle, FileSystemError> {
|
||||
return Result {
|
||||
try FileDescriptor.open(
|
||||
@@ -1226,7 +1227,7 @@ extension SystemFileHandle {
|
||||
SystemFileHandle(
|
||||
takingOwnershipOf: descriptor,
|
||||
path: path,
|
||||
executor: executor
|
||||
threadPool: threadPool
|
||||
)
|
||||
}.mapError { errno in
|
||||
FileSystemError.open("open", error: errno, path: path, location: .here())
|
||||
@@ -1238,7 +1239,7 @@ extension SystemFileHandle {
|
||||
mode: FileDescriptor.AccessMode,
|
||||
options originalOptions: FileDescriptor.OpenOptions,
|
||||
permissions: FilePermissions?,
|
||||
executor: IOExecutor,
|
||||
threadPool: NIOThreadPool,
|
||||
useTemporaryFileIfPossible: Bool = true
|
||||
) -> Result<SystemFileHandle, FileSystemError> {
|
||||
let openedPath: FilePath
|
||||
@@ -1351,7 +1352,7 @@ extension SystemFileHandle {
|
||||
takingOwnershipOf: descriptor,
|
||||
path: openedPath,
|
||||
materialization: materialization,
|
||||
executor: executor
|
||||
threadPool: threadPool
|
||||
)
|
||||
|
||||
return .success(handle)
|
||||
@@ -1365,7 +1366,7 @@ extension SystemFileHandle {
|
||||
mode: mode,
|
||||
options: originalOptions,
|
||||
permissions: permissions,
|
||||
executor: executor,
|
||||
threadPool: threadPool,
|
||||
useTemporaryFileIfPossible: false
|
||||
)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user