[英]Openmp with ofstream and system command
我使用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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.