ios - 使用 dispatch_sync 作为互斥锁

标签 ios objective-c multithreading grand-central-dispatch critical-section

这是我需要做的。 我希望 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 完成之前不会返回,这意味着 applicationDidBecomeActiverunCriticalSection 完成之前不会返回 执行。

这可能不是您想要的,因此您必须使用 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/

相关文章:

ios - 将libTiff中的Tiff数据类型转换为nsdata iOS

ios - 更新工具栏的 positionForBar

ios - 为什么 XMPP 函数什么都不返回?

ios - 核心数据 : error: (14) I/O error for database

ios - 如何快速将 UIViewController 添加到 UIScrollView 中?

ios - 带有 NSFetchedResultsController 错误的 moveRows

objective-c - 为什么我的 NSColor 类 NSConcreteData?

c# - 当前的 SynchronizationContext 可以为 null 吗?

java - 如何使用 ExecutorService 处理中止的 Runnable?

python - python Rlock 如何工作以及 Rlock 的所有者是什么?