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.

1

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Although this sounds more like you want a barrier
@MikeSeymour: Why don't you add it as an answer?
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!
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.

1 Comment

Actually, one semaphore signaled [n-1] times would be fine - no array necessary with a semaphore, unlike events.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.