27

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

实施“N 个进程屏障”,即确保一组进程中的每个进程在其各自执行的某个时间点等待其他进程到达它们的给定点。

您有以下可用操作:

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

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

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

4

3 回答 3

47

这在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
于 2011-06-13T15:21:16.120 回答
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])
于 2015-12-18T10:13:21.430 回答
0

只有 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])
于 2015-12-18T10:30:39.373 回答