Deinit and MainActor

Update: Pitch thread - Isolated synchronous deinit

I've a made PoC for isolated synchronous deinit - Comparing apple:main...nickolas-pohilets:mpokhylets/isolated-deinit · apple/swift · GitHub. Will make a pitch soon, but early feedback is welcomed.

I still need to make few changes to support @objc classes and update Sema rules to not generate isolated deinit if there is no custom deinitialising code.

  • Introduced new runtime function swift_task_performOnExecutor. If executor switch is needed, it wraps provided context pointer and work function into an AdHoc job and schedules it on the new executor. It doesn't do any reference counting is safe to be used from dealloc. Ad hoc job is created with priority of Task.currentPriority.

  • If deinit is isolated, then usual implementation of the __deallocating_deinit goes to a new function - __isolated_deallocating_deinit, and __deallocating_deinit (called from swift_release) becomes a thunk that schedules __isolated_deallocating_deinit on the correct executor.

// foo.swift
@MainActor
func mainFunc() {
    if Thread.isMainThread {
        print("MainThread!")
    } else {
        print("Not Main Thread")
    }
}

@MainActor
private final class Bar {
    deinit {
        mainFunc() // OK, deinit is isolated.
    }
}


2 Likes