gpt4 book ai didi

c++ - OpenMP 是否复制私有(private)对象?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:24 26 4
gpt4 key购买 nike

我正在编写一个读取大文件 (3x280 GB) 并对文件中的数据执行拟合程序的程序。并行化这样的程序非常方便,使用 OpenMP 可以轻松完成。

我不明白的是如何在 OpenMP 中获取私有(private)变量。众所周知,fstream 的对象是不可复制的,而且从直觉上讲,这使我无法将其用作私有(private)对象。所以文件的阅读者被共享了。

后来我遇到了一些问题,我想尝试将 fstreams 设为私有(private),......你猜怎么着?有效!!!这怎么可能?!如果对象是不可复制的,OpenMP 如何为每个内核使用同一对象的不同拷贝?

我的程序是这样的:

fstream dataReaderX(Dirs[0].c_str(), ios::in | ios::binary);
fstream dataReaderY(Dirs[1].c_str(), ios::in | ios::binary);
fstream dataReaderZ(Dirs[2].c_str(), ios::in | ios::binary);
#pragma omp parallel num_threads(cpus_num) shared(...) private(...,dataReaderX,dataReaderY,dataReaderZ)
{
...
}

谢谢。

最佳答案

firstprivate 变量被复制,而不是 private - 对于后者,调用默认构造函数:

第 2.9.3.3 节 - private 子句:

The new list item is initialized, or has an undefined initial value, as if it had been locally declared without an initializer. The order in which any default constructors for different private variables of class type are called is unspecified. The order in which any C/C++ destructors for different private variables of class type are called is unspecified.

这是一个简单的演示代码:

#include <fstream>
#include <stdio.h>
#include <omp.h>

int main (void)
{
std::fstream reader("test.txt", std::ios::in);
printf("Main thread: reader.is_open() = %d\n", reader.is_open());
#pragma omp parallel private(reader)
{
printf("Thread %d: reader.is_open() = %d\n",
omp_get_thread_num(), reader.is_open());
}
return 0;
}

这是预期的输出:

Main thread: reader.is_open() = 1
Thread 1: reader.is_open() = 0
Thread 0: reader.is_open() = 0
Thread 3: reader.is_open() = 0
Thread 2: reader.is_open() = 0

一件有趣的事是,英特尔 C++ 编译器因内部错误(断言失败)而出错 - 使用版本 11.1、12.0 和 12.1 进行了测试。另一方面,GNU C++ 编译器遵循标准(上面的输出来自 g++)。当使用 firstprivate 时,两个编译器都会报错,尽管英特尔 C++ 编译器再次出现内部错误。

这听起来可能很愚蠢,但您是否检查过是否在您使用的特定编译器中启用了 OpenMP 支持?

关于c++ - OpenMP 是否复制私有(private)对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10999955/

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