【问题标题】:Implementing an N process barrier using semaphores使用信号量实现 N 个进程屏障
【发布时间】:2011-09-13 22:47:23
【问题描述】:

我目前正在为之前迭代的操作系统考试进行培训,我遇到了这个问题:

实施“N 流程屏障”,即 是,确保每个过程出来 一群人在等待,在某些 点在其各自的执行,对于 其他进程达到他们的 给定点。

你有以下 可用的操作:

init(sem,value), wait(sem) and signal(sem)

N 是一个任意数字。我可以使它适用于给定数量的进程,但不适用于任何数量。

有什么想法吗?用伪代码回复就可以了,这不是作业,只是个人学习。

【问题讨论】:

    标签: operating-system computer-science semaphore systems-programming barrier


    【解决方案1】:

    这在The Little Book of Semaphores 中得到了很好的呈现。

    n = the number of threads
    count = 0
    mutex = Semaphore(1)
    barrier = Semaphore(0)
    
    
    mutex.wait()
    count = count + 1
    mutex.signal()
    
    if count == n: barrier.signal() # unblock ONE thread
    
    barrier.wait()
    barrier.signal() # once we are unblocked, it's our duty to unblock the next thread
    

    【讨论】:

    • 谢谢!我想到了一些非常接近的东西。
    • if count... 放在互斥块中以确保它只输入一次会更好吗?它现在的样子看起来你可能会输入两次。
    • nvm - 看了看这本小书,它可以发出两次信号,因为这个屏障没有被重用,所以它的最终状态并不重要,只要它实现了它的目标。
    • 举个例子:假设线程 5 获取互斥锁,递增计数并释放互斥锁。现在调度程序切换到另一个线程,该线程再次获取互斥锁,增加计数并释放互斥锁。现在计数为 6,并且屏障永远不会发出线程信号。
    • 赞成参考信号量小书。这很棒!谢谢!
    【解决方案2】:

    使用 N 个信号量。不太确定...

    semaphore barr[N]
    semaphore excl=1
    int count=0
    
    int i=1
    while (i<=N)
       barr[i]=0 #initialization
       i=i+1
    
    # use, each thread (tid)
    wait(excl)
    count=count+1
    if (count==N)
       int j=1
       while (j<=N)
           signal(barr[j])
           j=j+1
       count=0
    signal(excl)
    wait(barr[tid])
    

    【讨论】:

    • 这会遇到错误。应该是while (i&lt;N)。下一个 while 循环也一样:while (j&lt;N).
    【解决方案3】:

    只有 2 个屏障信号量,但不确定...

    semaphore barr[0..1] # two semaphores: barr[0] and barr[1]
    semaphore excl=1
    int count=0
    int whichOne=0 # select semaphore to avoid race conditions
    
    barr[0]=0 #initialization
    barr[1]=0
    
    # sample use
    int current   #local for each thread
    wait(excl)
    current=whichOne
    count=count+1
    if (count==N)
       int j=1
       while (j<=N)
           signal(barr[current])
           j=j+1
       count=0
       whichOne=1-whichOne # swap barrier to avoid race conditions
    signal(excl)
    wait(barr[current])
    

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 2013-11-30
      • 2012-12-09
      • 2013-12-07
      • 2018-05-11
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      相关资源
      最近更新 更多