c++ multithreading synchronization

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 ie 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.


您应该检查Boost线程库,特别是有关条件变量的部分。


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.

链接地址: http://www.djcxy.com/p/56064.html

上一篇: 用HTML和CSS创建这个设计?

下一篇: c ++多线程同步