【问题标题】:How to fork a large number of threads in OpenMP?如何在 OpenMP 中分叉大量线程?
【发布时间】:2026-01-10 16:35:03
【问题描述】:

出于某种原因,我需要对我的处理器施加压力,并且我想在 OpenMP 中分叉很多线程。在 pthreads 中,您可以使用 for 循环轻松完成它,因为它分叉一个线程只是一个函数调用。但是在 OpenMP 中你必须有这样的东西:

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

我只是想知道是否有更简单的方法可以在 OpenMP 中分叉大量线程?

【问题讨论】:

  • 你的意思是:#pragma omp parallel ... num_threads(100)
  • @Mysticial 但我不想在并行区域内复制#pragma omp section,我只需要在 100 个线程上运行的两个部分,50 个运行部分 0 和 50 个运行部分 1,我该怎么做去做? (不确定我是否对此完全确定)。

标签: c multithreading openmp


【解决方案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)
}  

【讨论】:

    【解决方案2】:

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

    // 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();
        } 
    }
    

    【讨论】: