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

时间:2012-01-10 12:01:54

标签: objective-c ios semaphore

是否可以在ios应用程序中实现Counting Semaphore?

4 个答案:

答案 0 :(得分:14)

是的,有可能。 有很多同步工具可用:

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

我建议阅读“Threading Programming Guide”并询问更具体的内容。

答案 1 :(得分:7)

像这样:

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

答案 2 :(得分: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 :(得分: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()