1

I have a question regarding multithreaded loops in OpenMP. The private-clause declares variables in its list to be private to each thread. So far so good. But what happens when I call a function inside a multithreaded loop? See this minimal example:

#include <iostream>
#include <vector>
#include "omp.h"

using namespace std;



int second(int num)
{
    int ret2 = 2*num;
    return ret2;
}

int first(int num)
{
    int ret1 = num;
    return second(ret1);
}


int main()
{
    int i;
    #pragma omp parallel
    {
        vector<int> test_vec;
        #pragma omp for
        for(i=0; i<100; i++)
        {
            test_vec.push_back(first(omp_get_thread_num()));
        }
        #pragma omp critical
        cout << test_vec[0] << endl;
    }
    return 0;
}

Will each thread get its own version of the functions first and second such that the threads can call them independently of each other? Or will the threads have to "queue" in order not to call them at the same time?

Whatever happens, I would expect the variables ret1 and ret2 to be private to each thread

1 Answer 1

1

ret2 and ret1 are declared on the stack, and each thread will have its own stack, therefore there will be no interference if first or second get called by multiple threads simultaneously.

Am I understanding your question correctly?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you understood it correctly. I was worried that I had to include a clause such that interference would be avoided. But if each thread has its own private stack, where variables are declared, then there will be no interference to begin with, so all OK

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.