如何在 iOS 应用程序中实现信号量?

6

在iOS应用程序中是否可以实现计数信号量?

4个回答

17

是的,这是可能的。

有许多同步工具可供使用:

  • @synchronized
  • NSLock
  • NSCondition
  • NSConditionLock
  • GCD信号量
  • pthread锁
  • ...

我建议阅读《多线程编程指南》并询问更为具体的问题。


@synchronized 是我最喜欢的。如果没有明显的对象可以阻塞,可以使用全局对象,如静态 NSNumber。坚持使用一个信号量模型可能有助于提高可读性等方面的问题。 - Tom Andersen
在全局对象上同步是一个不好的想法。你不知道是否有其他代码也在同步它,因此你会面临死锁的风险。始终在具有有限可见性的东西上同步,明确为手头的任务而设。另外,永远不要在自身上同步;同样,你不知道还有什么其他东西可能正在使用相同的对象。 - occulus

8

像这样:

dispatch_semaphore_t sem = dispatch_semaphore_create(0);

[self methodWithABlock:^(id result){
    //put code here
    dispatch_semaphore_signal(sem);

    [self methodWithABlock:^(id result){
        //put code here
        dispatch_semaphore_signal(sem);
    }];
}];

dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

信用 http://www.g8production.com/post/76942348764/wait-for-blocks-execution-using-a-dispatch


这篇文章介绍了如何使用dispatch等待代码块的执行。

4

我找不到原生的IOS对象来完成这个任务,但是使用C库完全可以:

#import "dispatch/semaphore.h"
...
dispatch_semaphore_t activity;
...
activity = dispatch_semaphore_create(0);
...
dispatch_semaphore_signal(activity);
...
dispatch_semaphore_wait(activity, DISPATCH_TIME_FOREVER);

希望这能帮到你。

3
在Swift 3中,您可以使用DispatchSemaphore
// initialization
let semaphore = DispatchSemaphore(value: initialValue)

// wait, decrement the semaphore count (if possible) or wait until count>0
semaphore.wait()

// release, increment the semaphore count
semaphore.signal()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接