gpt4 book ai didi

c++ - 在多线程循环中调用函数

转载 作者:太空宇宙 更新时间:2023-11-04 11:56:32 24 4
gpt4 key购买 nike

我对 OpenMP 中的多线程循环有疑问。 private 子句声明其列表中的变量对每个线程都是私有(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 对每个线程都是私有(private)的

最佳答案

ret2ret1声明在栈上,每个线程都有自己的栈,所以first不会有干扰或 second 被多个线程同时调用。

我是否正确理解了您的问题?

关于c++ - 在多线程循环中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15979953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com