【问题标题】:Waiting for asynchronous calls in a swift script在 swift 脚本中等待异步调用
【发布时间】:2015-02-27 20:28:44
【问题描述】:

我正在编写一个在终端中运行的快速脚本,该脚本向后台线程调度几个操作。没有任何额外的努力,在我完成所有调度之后,代码到达文件末尾并退出,同时也终止了我的后台操作。在我的后台操作完成之前保持 swift 脚本处于活动状态的最佳方法是什么?

我想出的最好的方法如下,但我不认为这是最好的方法,甚至是正确的。

var semaphores = [dispatch_semaphore_t]()
while x {
  var semaphore = dispatch_semaphore_create(0)
  semaphores.append(semaphore)
  dispatch_background {
    //do lengthy operation
    dispatch_semaphore_signal(semaphore)
  }
}

for semaphore in semaphores {
  dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}

【问题讨论】:

标签: swift asynchronous command-line


【解决方案1】:

除了使用dispatch_groups,还可以进行以下操作:

yourAsyncTask(completion: {
    exit(0)
})

RunLoop.main.run()

一些资源:

【讨论】:

    【解决方案2】:

    感谢 Aaron Brager,他与 Multiple workers in Swift Command Line Tool,

    这是我用来寻找答案的方法,使用 dispatch_groups 来解决问题。

    【讨论】:

      【解决方案3】:

      这样的事情怎么样:

      func runThingsInTheBackground() {
          var semaphores = [dispatch_semaphore_t]()
      
          for delay in [2, 3, 10, 7] {
              var semaphore = dispatch_semaphore_create(0)
              semaphores.append(semaphore)
      
              dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
                  sleep(UInt32(delay))
                  println("Task took \(delay) seconds")
      
                  dispatch_semaphore_signal(semaphore)
              }
          }
      
          for semaphore in semaphores {
              dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
          }
      }
      

      这与您所拥有的非常相似。我的工作“队列”是一系列要休眠的秒数,因此您可以看到背景中正在发生的事情。

      请注意,这只是在后台运行所有任务。如果您想将活动任务的数量限制为例如 CPU 内核的数量,那么您需要做更多的工作。

      不确定这是否是您要查找的内容,请告诉我。

      【讨论】:

      • 也许我的问题不清楚,但这基本上正是我在上面发布的内容。不过感谢您的帖子!
      • 我的例子有效。什么不见​​了?我认为它回答了你的问题?
      • 我确定你的代码可以工作,但你的代码和我的几乎一样,并没有真正添加任何东西。
      • 它在后台运行任务,等待它们完成。如果这不是您想要的,请告诉我,我会更改代码以获得更好的答案。
      猜你喜欢
      • 2017-04-16
      • 1970-01-01
      • 2017-07-22
      • 2021-10-22
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      相关资源
      最近更新 更多