0

我需要在多个进程之间进行一些同步,例如 POSIX 信号量或共享串行调度队列。OS X中的swift是否有类似的东西。

4

2 回答 2

1

命名信号量在 Swift 中可用:

import Darwin

var sema = sem_open("/mysema", O_CREAT, 0o666, 0)
guard sema != SEM_FAILED else {
    perror("sem_open")
    exit(EXIT_FAILURE)
}

defer { sem_close(sema) }

print("Waiting for semaphore")
sem_wait(sema)
print("Got semaphore")
于 2017-01-04T10:42:02.273 回答
0

正如 Martin R 指出的那样,这适用于线程,而不是进程。

是的,当然,您应该阅读有关 Grand Central Dispatch (GCD) 的信息。或在这里

WWDC 上有一个很好的视频

这是从此处获取的有关信号量的示例:

private func semaphoreExample2() {
    let semaphore = dispatch_semaphore_create(0)
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    dispatch_async(queue) {
        NSLog("Running async task...")
        sleep(3)
        NSLog("Async task completed")
        dispatch_semaphore_signal(semaphore)
    }
    NSLog("Waiting async task...")
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
    NSLog("Continue!")
}

或者从这里开始使用 Swift 3 中的另一个:

// creating the semaphore with a resource count of 1
let semaphore       = DispatchSemaphore( value: 1 )
let watchdogTime    = DispatchTime.now() + DispatchTimeInterval.seconds(1)
...

// synchronize access to a shared resource using the semaphore
if case .TimedOut = semaphore.wait(timeout: watchdogTime) {
    print("OMG! Someone was bogarting that semaphore!")
}
// begin access shared resource…
...

// end access to resource
semaphore.signal()
于 2017-01-04T09:36:49.973 回答