Repository: apple/swift-nio
File: Sources/NIOPosix/PosixSingletons+ConcurrencyTakeOver.swift (Swift)

Code before:
    ///
    /// This allows to use Swift Concurrency and retain high-performance I/O alleviating the otherwise necessary thread switches between
    /// Swift Concurrency's own global pool and a place (like an `EventLoop`) that allows to perform I/O
    ///
    /// This method uses an atomic compare and exchange to install the hook (and makes sure it's not already set). This unilateral atomic memory
    /// operation doesn't guarantee anything because another piece of code could have done the same without using atomic operations. But we
    /// do our best.
    ///
    /// - warning: You may only call this method from the main thread.
    /// - warning: You may only call this method once.
    @discardableResult
    public static func unsafeTryInstallSingletonPosixEventLoopGroupAsConcurrencyGlobalExecutor() -> Bool {
        #if compiler(>=5.9)
        guard #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) else {
            return false
        }

        typealias ConcurrencyEnqueueGlobalHook = @convention(thin) (
            UnownedJob, @convention(thin) (UnownedJob) -> Void
        ) -> Void

        guard
            _haveWeTakenOverTheConcurrencyPool.compareExchange(
                expected: false,
                desired: true,
                ordering: .relaxed
            ).exchanged
        else {
            fatalError("Must be called only once")
        }

        #if canImport(Darwin)
        guard pthread_main_np() == 1 else {
            fatalError("Must be called from the main thread")
        }
        #endif

        // Unsafe 1: We pretend that the hook's type is actually fully equivalent to `ConcurrencyEnqueueGlobalHook`
        //   @convention(thin) (UnownedJob, @convention(thin) (UnownedJob) -> Void) -> Void
        // which isn't formally guaranteed.
        let concurrencyEnqueueGlobalHookPtr = dlsym(
            dlopen(nil, RTLD_NOW),
            "swift_task_enqueueGlobal_hook"
        )?.assumingMemoryBound(to: UnsafeRawPointer?.AtomicRepresentation.self)
        guard let concurrencyEnqueueGlobalHookPtr = concurrencyEnqueueGlobalHookPtr else {
            return false
        }

        // We will use an atomic operation to swap the pointers aiming to protect against other code that attempts
        // to swap the pointer. This isn't guaranteed to work as we can't be sure that the other code will actually
        // use atomic compares and exchanges to. Nevertheless, we're doing our best.

Review comment (suggestion):
```suggestion
                ordering: .acquiringAndReleasing
```

This is probably safe without using an acquiring load here due to the `dlsym` call that follows it, but semantically this should be an acquiring load. Logically then it also has to be a releasing store because we're synchronising with ourselves!

Code after:
    ///
    /// This allows to use Swift Concurrency and retain high-performance I/O alleviating the otherwise necessary thread switches between
    /// Swift Concurrency's own global pool and a place (like an `EventLoop`) that allows to perform I/O
    ///
    /// This method uses an atomic compare and exchange to install the hook (and makes sure it's not already set). This unilateral atomic memory
    /// operation doesn't guarantee anything because another piece of code could have done the same without using atomic operations. But we
    /// do our best.
    ///
    /// - warning: You may only call this method from the main thread.
    /// - warning: You may only call this method once.
    @discardableResult
    public static func unsafeTryInstallSingletonPosixEventLoopGroupAsConcurrencyGlobalExecutor() -> Bool {
        #if /* minimum supported */ compiler(>=5.9) && /* maximum tested */ swift(<5.11)
        guard #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) else {
            return false
        }

        typealias ConcurrencyEnqueueGlobalHook = @convention(thin) (
            UnownedJob, @convention(thin) (UnownedJob) -> Void
        ) -> Void

        guard
            _haveWeTakenOverTheConcurrencyPool.compareExchange(
                expected: false,
                desired: true,
                ordering: .relaxed
            ).exchanged
        else {
            fatalError("Must be called only once")
        }

        #if canImport(Darwin)
        guard pthread_main_np() == 1 else {
            fatalError("Must be called from the main thread")
        }
        #endif

        // Unsafe 1: We pretend that the hook's type is actually fully equivalent to `ConcurrencyEnqueueGlobalHook`
        //   @convention(thin) (UnownedJob, @convention(thin) (UnownedJob) -> Void) -> Void
        // which isn't formally guaranteed.
        let concurrencyEnqueueGlobalHookPtr = dlsym(
            dlopen(nil, RTLD_NOW),
            "swift_task_enqueueGlobal_hook"
        )?.assumingMemoryBound(to: UnsafeRawPointer?.AtomicRepresentation.self)
        guard let concurrencyEnqueueGlobalHookPtr = concurrencyEnqueueGlobalHookPtr else {
            return false
        }

        // We will use an atomic operation to swap the pointers aiming to protect against other code that attempts
        // to swap the pointer. This isn't guaranteed to work as we can't be sure that the other code will actually
        // use atomic compares and exchanges to. Nevertheless, we're doing our best.