创建初始值为0的信号量会导致执行问题 [英] Creating semaphore with initial value of 0 make issues with execution

查看:636
本文介绍了创建初始值为0的信号量会导致执行问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习GCD,但对信号量有疑问. 这是我的代码:

I'm learning GCD and got question about semaphore. Here is my code:

class ViewController: UIViewController {

    var semaphore: dispatch_semaphore_t! = nil

  override func viewDidLoad() {
    super.viewDidLoad()

    semaphore = dispatch_semaphore_create(0)


    dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) {
      print("Entering")

      self.semaphoreTask()
      print(self.semaphore.debugDescription)
    }

    semaphoreTask()
     print(semaphore.debugDescription)
  }


  func semaphoreTask() {
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
    for i in 0...1000 {
      print(i)
      if i == 1000 {
        print("i is equal to 10000!")
      }
    }
    dispatch_semaphore_signal(self.semaphore)
  }

如果我运行此代码,则semaphoreTask中的任何内容都不会打印在控制台中,但是如果我更改

If I run this code so nothing from semaphoreTask is printed in the console, but if I change

semaphore = dispatch_semaphore_create(0)

semaphore = dispatch_semaphore_create(1)

一切正常.

问题是为什么我应该写dispatch_semaphore_create(1)而不是0?

The question is why should I write dispatch_semaphore_create(1) but not 0?

谢谢!

推荐答案

您可以通过两种不同的方式使用信号量:

You can use the semaphore in 2 different ways:

  1. 说出工作或资源准备就绪的时间. 在这种情况下,您可以将信号量从0开始.准备就绪时,创建者将调用signal.消费者致电wait等待所需的商品/资源.
  2. 限制并发操作/请求/使用的数量. 在这种情况下,您可以以正值(例如4)启动信号量.每个用户都调用wait,并且如果有资源,则允许他们继续.如果没有,它们将被阻止.每个人完成资源使用后,便调用signal.
  1. To say when work or a resource is ready. In this case you start the semaphore at 0. The creator calls signal when something is ready. The consumer calls wait to wait for the expected item / resource.
  2. To limit the number of concurrent operations / requests / usages. In this case you start the semaphore at a positive value, like 4. The users each call wait and if resource is available they are allowed to continue. If not they are blocked. When each has finished with the resource they call signal.

因此,您看到的是预期的效果,因为您将信号量设置为就绪标志,但将其用作访问限制(因为首先调用wait).

So, what you see it expected because you're setting the semaphore up as a ready flag but using it as an access limit (because you call wait first).

这篇关于创建初始值为0的信号量会导致执行问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆