gpt4 book ai didi

c++ - 带有 ofstream 和系统命令的 Openmp

转载 作者:太空狗 更新时间:2023-10-29 23:13:43 25 4
gpt4 key购买 nike

我在使用 openmp 时遇到问题

在并行化的其他操作中,我需要读取一个文件,编辑内容并将其保存到另一个文件中,以便为入口提供一个我将要启动的可执行文件

出于性能原因,循环实际上是递归是并行化的。

问题是有时我编写并关闭的输入文件无法被我的外部可执行文件读取

你有想法吗?谢谢

为了以最简单的方式重现该问题,我创建了一个小程序:

#include <iostream>
#include <ctime>
#include <fstream>
#include <omp.h>
#include <vector>
#include <algorithm>
#include <string>
#include <stdlib.h>
#include <cstdio>
#include <sstream>

using namespace std;

int main()
{
const int max = 1000;
int N;
int nthreads = 0;
int threadid = 0;
time_t t=time(NULL);
stringstream s;
#pragma omp parallel private(threadid)
{
#pragma omp master
{
nthreads = omp_get_num_threads();
cout << endl << nthreads << " thread(s) disponible" << endl;
}
#pragma omp barrier
threadid = omp_get_thread_num();
#pragma omp critical
{
cout << "Thread " << threadid << " OK" << endl;
}
}
ifstream f("R:\\SIM.net", ios::in);
if (f)
{
s << f.rdbuf();
}
else
{
cout << "Impossible d'ouvrir le fichier d'entrée" << endl;
}
f.close();
#pragma omp parallel for schedule(dynamic)
for (N = 1; N <= max; N++)
{
ofstream o;
string l = "R:\\SIM\\"+to_string(N) + ".net";
o.open(l, ios::out | ios::trunc);
if (o)
{
o << s.str();
}
else
{
cout << "Impossible d'ouvrir le fichier de sortie" << endl;
}
o.close();
string commande = "\"R:\\LTspiceIV\\scad3.exe\" -b "+l+" &";
int retour= system(commande.c_str());
}
#pragma omp barrier
cout << "FIN" << endl << endl;
cout << "Temps : " << difftime(time(NULL), t) << " s" << endl;
return 0;
}

最佳答案

感谢您的回答 NoseKnowsAll

事实上我已经尝试过添加一个临界区但是更糟

4/1000 文件在没有关键的情况下不可读,56/1000 文件不可读,严重

for (N = 1; N <= max; N++)
{
string l = "R:\\SIM\\"+to_string(N) + ".net";
#pragma omp critical
{
ofstream o;
o.open(l, ios::out | ios::trunc);
if (o)
{
o << s.str();
}
else
{
cout << "Impossible d'ouvrir le fichier de sortie" << endl;
}
o.close();
}
string commande = "\"R:\\LTspiceIV\\scad3.exe\" -b "+l+" &";
int retour= system(commande.c_str());
}

关于c++ - 带有 ofstream 和系统命令的 Openmp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37416835/

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