2015-01-27 31 views
0

由于某些原因,我需要强调我的处理器,并且我想在OpenMP中分配很多线程。在pthread中,你可以很容易地使用for循环来完成它,因为它分叉的线程只是一个函数调用。但在OpenMP的,你必须有这样的事情:如何在OpenMP中派生大量线程?

#pragma omp parallel sections 
{ 
    #pragma omp section 
    { 
     //section 0 
    } 
    #pragma omp section 
    { 
     //section 1 
    } 
    .... // repeat omp section for n times 
} 

我只是想知道是否有叉大量的OpenMP线程的任何更简单的方法?

+5

你的意思是这样的:'的#pragma OMP并行... NUM_THREADS(100)' – Mysticial 2015-01-27 00:57:01

+0

@Mysticial但我不想复制''的#pragma OMP section''并行区域里面,我只需要两个部分运行100个线程,50个运行部分0和50个运行部分1,我该怎么做? (不知道我是否绝对确信这一点)。 – dorafmon 2015-01-27 01:17:23

回答

1

你不需要做任何特别的事情,差不多。只需编写计算密集型任务的代码并将其放入并行区域即可。然后指出你想要的线程数。为此,您使用omp_set_dynamic(0)来禁用动态线程(这有助于实现所需的线程数,但仍不能保证),然后omp_set_num_threads(NUM_THREADS)来指示您想要的线程数。

然后每个线程都会克隆你在代码中指明的任务。就那么简单。

const int NUM_THREADS = 100; 
omp_set_dynamic(0); 
omp_set_num_threads(NUM_THREADS); 
#pragma omp parallel 
{ 
    // How many threads did we really get? Let's write it once only. 
    #pragma omp single 
    { 
     cout << "using " << omp_get_num_threads() << " threads." << std::endl; 
    } 
    // write some compute-intensive code here 
    // (be sure to print the result at the end, so that 
    // the compiler doesn't throw away useless instructions) 
} 
0

要做你想要的,你得到线程号,然后根据你是哪个线程做不同的事情。

// it's not guaranteed you will actually get this many threads 
omp_set_num_threads(NUM_THREADS); 

int actual_num_threads; 
#pragma omp parallel 
{ 
    #pragma omp single 
    { 
     actual_num_threads = omp_get_num_threads(); 
    } 

    int me = omp_get_thread_num(); 

    if (me < actual_num_threads/2) { 
     section1(); 
    } 
    else { 
     section2(); 
    } 
}