gpt4 book ai didi

c++ - 使用 openMP v. 2.0 并行化过滤器迭代器

转载 作者:行者123 更新时间:2023-11-27 23:58:04 24 4
gpt4 key购买 nike

我有一个大 vector 。我想同时增加正成员。

class is_positive_number {
public:
bool operator()(int x) { return 0 < x; }
};

int main()
{
int numbers_[] = { 0, -1, 4, -3, 5, 8, -2, 3, 4, -1 };
const int N = sizeof(numbers_) / sizeof(int);
std::vector<int> test_vec(numbers_, numbers_ + N);

std::cout << "max: " << omp_get_max_threads() << std::endl;
int number_of_threads = 4;
int SubVecLen = N / number_of_threads,
LeftOvers = N % number_of_threads;
int k = 0, i = 0, n = 0;
std::vector<int> start_vec, end_vec;
while (n < number_of_threads)
{
k += i;
i = (SubVecLen + (LeftOvers-- > 0 ? 1 : 0));
start_vec.push_back(k);
end_vec.push_back((k + i - 1));

++n;
}
for (size_t n = 0; n < number_of_threads; n++)
{
std::cout << start_vec[n] << "\t" << end_vec[n] << "\n";
}

is_positive_number predicate;
typedef boost::filter_iterator<is_positive_number, std::vector<int>::iterator>
FilterIter;

#pragma omp parallel
{
#pragma omp for
for (int s = 0; s < 4; s++)
{
FilterIter filter_iter_first(predicate, test_vec.begin(), (test_vec.begin() + start_vec[omp_get_thread_num()]) );
FilterIter filter_iter_last(predicate, test_vec.begin(), (test_vec.begin() + end_vec[omp_get_thread_num()] + 1) );

for (auto iter = filter_iter_first;
iter != filter_iter_last; iter++)
{
std::cout << "num: " << *iter << std::endl;
(*iter) = (*iter) + 1;
}

}
}

for (size_t n = 0; n < test_vec.size(); n++)
{
std::cout << test_vec[n] << "\n";
}
return 0;
}

结果错误!

然而,我要解决的实际问题比这个问题更复杂。我试图简化我的问题,以便更容易理解。我还必须提到,我只能使用 openMP v.2.0。这就是为什么我尝试拆分 vector 并将 vector 的每个部分专用于特定线程的原因。

任何想法将不胜感激。

最佳答案

您在创建过滤器迭代器时使用了错误的开始和停止索引。我附上了一个工作示例。我使用 s 在并行 for 语句中选择线程。不确定您的版本是否也适用,所以我将其更改为我习惯的版本。

#pragma omp parallel
{
#pragma omp for
for (int s = 0; s < 4; s++)
{
/* The following lines are important */
FilterIter filter_iter_first(predicate, test_vec.begin() + start_vec[s], (test_vec.begin() + end_vec[s] + 1));
FilterIter filter_iter_last(predicate, test_vec.begin() + end_vec[s] + 1, (test_vec.begin() + end_vec[s] + 1));

for (auto iter = filter_iter_first; iter != filter_iter_last; iter++)
{
std::cout << "num: " << *iter << std::endl;
(*iter) = (*iter) + 1;
}
}
}

关于c++ - 使用 openMP v. 2.0 并行化过滤器迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41098025/

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