Take the 2-minute tour ×

I want my threads to stop at a barrier point, but I want to only stop if a barrier is required. For example after a certain timer interval, I want all of threads to form a barrier. Is there a method to put a potential barrier point? For example at start of each function. I want something like this.

void some_function()

So I want potentially_barrier_wait to only call a barrier if its required, otherwise potentially_barrier_wait do nothing. Can this thing be implemented satisfactorily? Will this also work in programs which already have barriers in them, or will it race with them.

share|improve this question
Just wrap the barrier in an if-statement with whatever your condition is? –  Mysticial Sep 13 '12 at 17:44
Mystical - That is my question, Can this be done without introducing race conditions, especially in a program that already has barriers. –  user1018562 Sep 13 '12 at 17:46
Oh ic, you're afraid of a race condition in say - the if-condition. –  Mysticial Sep 13 '12 at 17:47
depends on your condition. If your condition requires some non-atomic resource, you'll have to wrap the whole thing in a mutex. - so inside your if statement, write a small inline that closes and opens a mutex before checking the condition. –  Woodrow Douglass Sep 13 '12 at 17:47
how are you implementing a barrier wait? –  Claudiu Sep 13 '12 at 17:49
add comment

1 Answer

Depends on what you mean by barrier... if you are referring to simple synchronization, you can do it like this:

On Windows, create an event CreateEvent( 0, false, 0, 0 ). In your thread, do a WaitForSingleObject on that. In your "controlling" thread, SetEvent it to let it pass your barrier. You can play with it to have it pre-set, and auto-release, etc.

On Linux, similar but you can use a pthread_cond_timedwait as your barrier, and signal it with pthread_cond_signal.

share|improve this answer
The OP is asking about rendezvous barriers, as seen in pthread_barrier_*() –  ninjalj Sep 13 '12 at 22:18
Although the implementation of a barrier using a conditional variable will be complex for small programs it is possible; Mark is on the right path with his answer. If you look at the source for pthread_barrier_wait it is simply a conditional variable across all threads. –  Yasky Feb 14 '13 at 16:03
add comment

Your Answer


