Take the 2-minute tour ×

this is a basic example of a barrier, of how some threads are waited to enter a barrier for an entrance and another barrier for an exit.
Although the code is fine, I don't really understand in depth how it works...
For instance, I don't understand why a thread that enters the barrier() function, after it does n = n-1, can immediately make n = n+1 and so influence the global n ...? why it seems like all the threads after they make n = n-1 stop somewhere , and then they make n = n+1 in synchronization?

import threading
import time
import random
bar1= threading.Semaphore(value=0)
bar2= threading.Semaphore(value=0)
region= threading.Semaphore(value=1)
threads= 10
n= thread
threadlist= []
def usage(x):
    for i in range(2):
        print "[ENTER]: ",x
        print "[EXIT]: ",x

def barrier():
    global bar1,bar2, region,n,threads
    n = n - 1;
    if n==0:
        for i in range(threads):
    n = n + 1
    if n == threads:
        for i in range(threads):

for i in range(threads):
    thread = threading.Thread(target=usage, args=(i,)) 
for i in range(len(threadlist)):
share|improve this question
Could you explain where this code came from and what its goal is? –  David Heffernan Mar 13 '11 at 19:19
This sounds to me like some homework; in this case, my personal suggestion is to just throw it away and implement it from the scratch, because the quality of the fragment is quite poor. –  Roberto Liffredo Mar 13 '11 at 19:25
@Roberto Liffredo. No it's not a homework, it's an example made at the lab..which i didnt understand. if it's poor can you come back with a better variant? thanks –  shaku Mar 13 '11 at 19:29
@David. the goal is purely theoretical. –  shaku Mar 13 '11 at 19:31
@shaku Do you mean to say don't know what it's supposed to do? If you don't care what it should do, why should we? –  David Heffernan Mar 13 '11 at 19:32
show 12 more comments

1 Answer

n is the number of threads that still have to reach the rendezvous point. region is a mutex, protecting access to n. bar1 and bar2 are semaphores, indicating the number of threads that can proceed, initialized to 0.

In the first part of barrier(), each thread enters in turn, decreases n, and blocks on the bar1 semaphore. The last thread to enter (the one that makes n == 0) posts the semaphore threads times, allowing that many threads to proceed.

The second part is symmetrical to the first, this time waiting for the last thread to increment n.

share|improve this answer
thank you! now it's very clear... the key instruction was bar1.acquire(); which makes the thread which calls it to block. –  shaku Mar 13 '11 at 19:28
add comment

Your Answer


