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

How to ask a semaphore for returning immediately rather than wait for signal?

我想高效地实施此行为:

函数被要求 运行(由用户)。知道这个函数也会被定时器自动重复调用,我想确保函数 returns 只要它已经 运行ning.

在伪代码中:

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:) 来测试 信号。如果信号量计数为零,则此 returns .timedOut, 否则它 returns .success (并减少信号量计数)。

let isRunning = DispatchSemaphore(value: 1)

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

    // doing the job
}