使用dispatch_sync作为互斥锁

这是我需要做的。 我希望dispatch_sync是使用GCD的最好方法

我有一些关键部分的代码放在Appdelegate的applicationDidBecomeActivecallback中。

我在dispatch_sync调用中封装了这个方法,所以无论调用了多less次的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()在块完成之前不会返回,这意味着在runCriticalSection完成执行之前, applicationDidBecomeActive不会返回。

这可能不是你想要的,所以你必须使用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); }); } 

runCriticalSection方法将被多次调用,而不是同时调用,所以我不知道这是你想实现的。

dispatch_sync只是将指定的块添加到串行队列(默认优先级全局队列),因此如果applicationDidBecomeActive在一行中被触发两次,则队列将包含两个将运行runCriticalSection块。 第一个开始执行,第二个开始执行,所以不会同时执行这两个块。

这是预期的行为? 如果是这样, dispatch_sync是要走的路。

作为附加组件:如果runCriticalSection执行繁重的操作,请考虑dispatch_sync将阻止运行applicationDidBecomeActive方法的线程(如果您不从另一个线程手动调用方法,则为主线程)直到该操作完成。

如果你想避免这种情况,你应该这样做:

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self runCriticalSectionOnComplete:^{ // If you want to perform something on completion, place it here. This is called asynchronously, without blocking the main thread. }]; }); 

dispatch_async将在块添加到队列后立即返回,而dispatch_sync等待块内的代码完成。

Interesting Posts