这是我需要做的。
我希望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()
在块完成之前不会返回,这意味着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);
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)