我需要在多个进程之间进行一些同步,比如POSIX信号量或共享串行调度队列。在OS X中是否存在与swift类似的东西。
答案 0 :(得分: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")
答案 1 :(得分:0)
正如Martin R所指出的,这在线程之间起作用,而不是在进程之间。
是的,当然,您should read关于Grand Central Dispatch(GCD)。或here。
WWDC的一个好视频是here。
以下是从here获取信号量的示例:
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!")
}
或者来自here的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()