Implementing an N process barrier using semaphores

后端 未结 3 1530
耶瑟儿~
耶瑟儿~ 2020-12-02 17:16

I\'m currently training for an OS exam with previous iterations and I came across this:

Implement a "N Process Barrier", that is, making sure t

相关标签:
3条回答
  • 2020-12-02 17:56

    This is well presented in 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
    
    0 讨论(0)
  • 2020-12-02 18:04

    Using N semaphores. Not very sure...

    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])
    
    0 讨论(0)
  • 2020-12-02 18:06

    Only 2 barrier semaphores, but not sure...

    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])
    
    0 讨论(0)
提交回复
热议问题