7

Here is a simplified version of my problem.

There are N threads executing following 3 instructions in an infinite loop:

A -> B -> C -> A -> B -> C -> A -> B -> .......

I want that all threads execute instruction B concurrently i.e. execution of B by any thread should start only if all threads have reached B. So, if there is a thread that has executed B -> C -> A, it should wait here till other threads are also ready to execute B.

If possible, please let me know a portable solution that'll work on both windows & MAC.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
arvin
  • 113
  • 1
  • 5
  • Only yesterday **[Bartosz Milewski posted his vidcast on C++11 Concurrency Series: 9. Condition Variables](http://bartoszmilewski.wordpress.com/2011/11/13/c11-concurrency-series-9-condition-variables/)**. I found it the most entertaining in the series (no need to view the others first, I think) – sehe Nov 14 '11 at 13:32

2 Answers2

4

You should check out the Boost thread library, especially the section about condition variables.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 7
    Although this sounds more like you want a [barrier](http://www.boost.org/doc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.barriers) – Mike Seymour Nov 14 '11 at 13:18
  • @MikeSeymour: Why don't you add it as an answer? – jgauffin Nov 14 '11 at 13:22
  • Thanks Mike, yes it appears that barrier is what I need. Let me get into its details & get back in case I face issues. Thanks again! – arvin Nov 14 '11 at 13:22
0

An array of N-1 semaphores and a mutex? All threads acquire the mutex, inc a counter and, if less than N, release the mutex and wait on the semaphore array at [counter]. The Nth thread finds the counter to be N, signals all the semaphores, resets the counter to 0, executes 'B' releases the mutex and exits. The other threads, when released, also execute B but cannot loop around and get in again until the Nth thread has executed 'B' and released the mutex.

All multitasking OS have semaphores/mutex. You could usee an event, if available, instead of the semaphore.

Martin James
  • 24,453
  • 3
  • 36
  • 60