【问题标题】:How to Implement Semaphores in iOS Application?如何在 iOS 应用程序中实现信号量?
【发布时间】:2012-02-06 20:17:28
【问题描述】:

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

【问题讨论】:

    标签: objective-c ios semaphore


    【解决方案1】:

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

    • @同步
    • NSLock
    • NS条件
    • NSConditionLock
    • GCD 信号量
    • 线程锁
    • ...

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

    【讨论】:

    • @synchonized 是我的最爱。如果没有明显的对象可以阻止,则将其与静态 NSNumber 之类的全局对象一起使用。坚持使用一种信号量模型可能有助于提高可读性等。
    • 在全局对象上同步是个坏主意。您不知道是否有任何其他代码也可能在其上同步,因此您将面临死锁的风险。始终同步一些可见性有限的东西,这些东西明确地用于手头的任务。另外,永远不要在自己上同步;再说一次,你不知道还有什么可能在使用同一个对象。
    【解决方案2】:

    像这样:

    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

    【讨论】:

      【解决方案3】:

      我无法找到一个本地 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);
      

      希望对您有所帮助。

      【讨论】:

        【解决方案4】:

        Swift 3 中,您可以使用 @987654321@

        // 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()
        

        【讨论】:

          猜你喜欢
          • 2012-05-16
          • 1970-01-01
          • 2013-08-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多