背景
我目前正在使用 objc_sync_enter / exit 对来管理锁:
func sync(lock: AnyObject, closure: () -> ())
{
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
func sync<T>(lock: AnyObject, closure: () -> T ) -> T
{
var t : T
objc_sync_enter(lock)
t = closure()
objc_sync_exit(lock)
return t
}
我可以使用这些机制来更新信号量,其中我将完成我需要完成的任务。
现在,在一个单独的线程中,我想等待直到我的信号量达到零,可能使用类似pthread信号量或某种廉价/轻旋转锁的东西?
var semaphore = 2 // ->0 using sync() when all preparation is complete
fun call_me_when_semaphore_becomes_zero() { }
问题
如何使用swift / iOS同步机制等待布尔条件?
如果界面看起来像这样会很好:
// implementation
func sync_wait(lock: AnyObject, condition: (()->Bool), closure: (() -> ()))
{
// NEED HELP HERE -------------------------------------------------------
// using lock, wait until condition becomes true, and then call closure
// ----------------------------------------------------------------------
}
// call
sync_wait( semaphore, condition: { semaphore==0 }, closure: { call_me_when_semaphore_becomes_zero() } )