Bob Fang
Bob Fang

Reputation: 7411

How to fork a large number of threads in OpenMP?

for some reason I need to stress my processor and I want to fork a lot of threads in OpenMP. In pthreads you can easily do it using a for loop since it is forking a thread is just a function call. But in OpenMP you have to have something like this:

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

I am just wondering if there is any easier way to fork a large number of threads in OpenMP?

Upvotes: 0

Views: 560

Answers (2)

MVTC
MVTC

Reputation: 855

To do what you want, you get the thread number and then do different things based on which thread you are.

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

Upvotes: 0

Manuel M
Manuel M

Reputation: 157

You don't need to do anything special, almost. Just write code for a compute-intensive task and put it inside a parallel region. Then indicate what number of threads you want. In order to do that, you use omp_set_dynamic(0) to disable dynamic threads (this helps to achieve the number of threads you want, but it still won't be guaranteed), then omp_set_num_threads(NUM_THREADS) to indicate what number of threads you want.

Then each thread will clone the task you indicate in the code. Simple as that.

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)
}  

Upvotes: 1

Related Questions