C ++ multi-threaded synchronization

Here is a simplified version of my problem.

In an infinite loop there are N threads executing the following 3 commands:

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

I want all threads to execute command B at the same time, that is, executing B by any thread should only start if all threads reach B. So, if there is a thread that executed B β†’ C β†’ A, it should wait here until other threads will also not be ready to execute B.

If possible, let me know a portable solution that will work on both Windows and MAC.

+7
source share
2 answers

You should check the Boost thread library , especially the section state variables .

+4
source

Array of semaphores N-1 and mutex? All threads acquire a mutex, including a counter, and if less than N, free the mutex and expect a semaphore array on [counter]. The nth thread finds the counter equal to N, signals all semaphores, resets the counter to 0, executes "B", releases the mutex and outputs. Other threads, when released, also execute B, but cannot loop and re-enter until the Nth thread executes "B" and releases the mutex.

All multi-tasking OS have semaphores / mutexes. You can use an event, if available, instead of a semaphore.

0
source

All Articles