在多线程循环中调用函数

时间:2013-04-12 20:04:25

标签: c++ multithreading openmp

我对OpenMP中的多线程循环有疑问。 private - 子句声明其列表中的变量对每个线程都是私有的。到现在为止还挺好。但是当我在多线程循环中调用函数时会发生什么?看到这个最小的例子:

#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;
}

每个线程是否会获得自己的函数版本firstsecond,以便线程可以相互独立地调用它们?或者线程是否必须“排队”才能不同时调用它们?

无论发生什么,我都希望变量ret1ret2对每个线程都是私有的

1 个答案:

答案 0 :(得分:1)

在堆栈上声明了

ret2ret1,并且每个线程都有自己的堆栈,因此如果firstsecond被调用,则不会受到干扰同时多个线程。

我能正确理解你的问题吗?

相关问题