Custom actor executor incorrect dispatch

The following implementation always prints true if the actor method doIt is called async from the main thread:

actor CustomActor: SerialExecutor {
    
    let queue = DispatchQueue(label: "SerialExecutorQueue")
    
    nonisolated func enqueue(_ job: consuming ExecutorJob) {
        let job = UnownedJob(job)
        queue.sync {
            job.runSynchronously(on: unownedExecutor)
        }
    }
    
    nonisolated var unownedExecutor: UnownedSerialExecutor {
        asUnownedSerialExecutor()
    }
    
    func doIt() {
        print(Thread.isMainThread)
    }

}

Is my implementation wrong, or is this some kind of runtime bug?

1 Like

DispatchQueue.sync() will typically run the block on the current thread.

1 Like

Correct: the canonical implementation of enqueue is not .sync but .async.

1 Like

Indeed, you are right:

sync(execute:)

As a performance optimization, this function executes blocks on the current thread whenever possible, with one exception: Blocks submitted to the main dispatch queue always run on the main thread.
1 Like