Swift 如何要求信号量立即返回而不是等待信号?

Swift 如何要求信号量立即返回而不是等待信号?,swift,grand-central-dispatch,semaphore,Swift,Grand Central Dispatch,Semaphore,我希望有效地实施这种行为: (由用户)要求运行一个函数。知道这个函数也会被计时器自动重复调用,我想确保这个函数在运行时返回 在伪代码中: var isRunning = false func process() { guard isRunning == false else { return } isRunning = true defer { isRunning = false } // doing the job } 我知道

我希望有效地实施这种行为:

(由用户)要求运行一个函数。知道这个函数也会被计时器自动重复调用,我想确保这个函数在运行时返回

在伪代码中:

var isRunning = false

func process() {

    guard isRunning == false else { return }

    isRunning = true

    defer {
        isRunning = false
    }

    // doing the job
}
我知道信号量的概念:

let isRunning = DispatchSemaphore(value: 1)

func process() {

    // *but this blocks and then passthru rather than returning immediately if the semaphore count is not zero.    
    isRunning.wait()

    defer {
        isRunning.signal()
    }

    // doing the job
}
如何使用信号量或任何其他解决方案来实现此行为?

您可以使用超时值为
now()
wait(timeout:)
来测试 信号灯。如果信号量计数为零,则返回
.timedOut
, 否则返回
.success
(并减少信号量计数)

let isRunning = DispatchSemaphore(value: 1)

func process() {
    guard isRunning.wait(timeout: .now()) == .success  else {
        return // Still processing
    }
    defer {
        isRunning.signal()
    }

    // doing the job
}