这是我需要做的。 我希望 dispatch_sync 是使用 GCD 的最佳方式
我在 Appdelegate 的 applicationDidBecomeActive 回调中有一段临界区代码..
我将该方法包装在一个 dispatch_sync 调用中,这样无论 applicationDidBecomeActive 被调用多少次,它都只会被调用一次
- (void)applicationDidBecomeActive:(UIApplication *)application{
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Thread created");
//crtical code
[self runCriticalSection];
});}
这是使用 dispatch_sync 的正确方法吗?
最佳答案
dispatch_sync()
在 block 完成之前不会返回,这意味着
applicationDidBecomeActive
在 runCriticalSection
完成之前不会返回
执行。
这可能不是您想要的,因此您必须使用 dispatch_async()
(已经
在另一个答案中说明)。
但是您不想启动另一个 runCriticalSection
如果前一个仍在运行。这可以通过“计数信号量”来实现
(这也是 GCD 的一个特性):
static dispatch_semaphore_t sema; // The semaphore
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Initialize with count=1 (this is executed only once):
sema = dispatch_semaphore_create(1);
});
// Try to decrement the semaphore. This succeeds if the count is still 1
// (meaning that runCriticalSection is not executing), and fails if the
// current count is 0 (meaning that runCriticalSection is executing):
if (dispatch_semaphore_wait(sema, DISPATCH_TIME_NOW) == 0) {
// Success, semaphore count is now 0.
// Start asynchronous operation.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//critical code
[self runCriticalSection];
// Increment the semaphore count (from 0 to 1), so that the next call
// to applicationDidBecomeActive will start a new operation:
dispatch_semaphore_signal(sema);
});
}
关于ios - 使用 dispatch_sync 作为互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16326131/