使用GCC和OMP在C中的特定线程顺序

时间:2013-01-05 00:41:02

标签: c++ c multithreading gcc openmp

我需要组建4个团队,每个团队有4个线程,每个团队都有连续的处理器。

我期待的结果是,例如:

Team 0 Thread 0 Processor: 0
Team 0 Thread 1 Processor: 1
Team 0 Thread 2 Processor: 2
Team 0 Thread 3 Processor: 3
Team 1 Thread 0 Processor: 4
Team 1 Thread 1 Processor: 5
Team 1 Thread 2 Processor: 6
Team 1 Thread 3 Processor: 7
Team 2 Thread 0 Processor: 8
Team 2 Thread 1 Processor: 9
Team 2 Thread 2 Processor: 10
Team 2 Thread 3 Processor: 11
Team 3 Thread 0 Processor: 12
Team 3 Thread 1 Processor: 13
Team 3 Thread 2 Processor: 14
Team 3 Thread 3 Processor: 15

我可以使用GOMP_CPU_AFFINITY变量处理GCC中的Processor Affinity。

我正在使用:

#pragma omp parallel num_threads(4)

两次以获得2个叉级。

目前我在GOMP_CPU_AFFINITY中订购此订单:

0 4 8 12 1 2 3 5 6 7 9 10 11 13 14 15

所以第一个叉子,“父亲叉子”得到:

Team 0 Thread 0 Processor: 0
Team 1 Thread 0 Processor: 4
Team 2 Thread 0 Processor: 8
Team 3 Thread 0 Processor: 12

我遇到的问题是第二组叉子没有任何顺序,所以,例如我可能有这种情况(我使用#pragma omp原子,所以只有一个'父亲'可以要求更多处理器任何时候):

Team 0 Thread 0 Processor: 0
Team 0 Thread 1 Processor: 5
Team 0 Thread 2 Processor: 6
Team 0 Thread 3 Processor: 7
Team 1 Thread 0 Processor: 4
Team 1 Thread 1 Processor: 13
Team 1 Thread 2 Processor: 14
Team 1 Thread 3 Processor: 15
Team 2 Thread 0 Processor: 8
Team 2 Thread 1 Processor: 1
Team 2 Thread 2 Processor: 2
Team 2 Thread 3 Processor: 3
Team 3 Thread 0 Processor: 12
Team 3 Thread 1 Processor: 9
Team 3 Thread 2 Processor: 10
Team 3 Thread 3 Processor: 11

问题是:有没有办法按顺序进行第二次请愿?

我想我必须用锁或其他东西做一些同步方法......

提前致谢!

  • 哈维尔

1 个答案:

答案 0 :(得分:1)

最后我可以做到这一点,这是我的代码:

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>

int main(int argc, char *argv[]){
    int padre, hijo;

    int contador = 0;
    omp_set_nested(1);
    int suma;
    #pragma omp parallel private(padre) shared(contador) num_threads(4)
    {
        padre = omp_get_thread_num();

        {

            while(contador != padre){
                // Don't know what to put here
            };

            #pragma omp parallel private(hijo) shared(padre, contador) num_threads(4)
            {
                hijo = omp_get_thread_num();
                printf("\nFather: %d Son: %d Processor: %d\n", padre, hijo, sched_getcpu());
                #pragma omp master
                {
                    contador++;
                }
            }
        }
    }
}

注意:Padre是父亲,Hijo是Son,而Contador是西班牙语的反击:P

我现在面临的问题是,如果我使用-O3优化编译我的代码,则while循环'dissapear',除非我在循环中放置一个printf行。我想我应该在另一个问题上问这个问题!

谢谢大家!

  • 哈维尔