How to Implement Semaphores in iOS Application?

夙愿已清 提交于 2019-12-04 14:01:39

问题


Is it possible to implement Counting Semaphore in ios application?


回答1:


Yes, it is possible. There are quite a few synchronization tools available:

  • @synchronized
  • NSLock
  • NSCondition
  • NSConditionLock
  • GCD semaphores
  • pthread locks
  • ...

I'd suggest reading "Threading Programming Guide" and asking something more specific.




回答2:


Like this:

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);

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




回答3:


I was unable to find a native IOS object to do this but it works just fine using the C library:

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

Hope that helps.




回答4:


In Swift 3 you can use a 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()


来源:https://stackoverflow.com/questions/8802949/how-to-implement-semaphores-in-ios-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!