Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

operating system - Implementing an N process barrier using semaphores

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 that each process out of a group of them waits, at some point in its respective execution, for the other processes to reach their given point.

You have the following ops available:

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

N is an arbitrary number. I can make it so that it works for a given number of processes, but not for any number.

Any ideas? It's OK to reply with the pseudo-code, this is not an assignment, just personal study.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...