【发布时间】:2016-09-21 20:37:46
【问题描述】:
我在使用 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;
}
【问题讨论】:
-
R 是完美的软内存盘
-
单线程没有这个问题:omp_set_num_threads(1)
-
IO 通常不可能在没有锁定和关键区域的情况下并行执行,就像您在第一个并行循环中所做的那样。即使可以创建,您也不太可能从并行运行中获得任何好处,因为您的所有线程都必须使用从内存到硬盘的相同路径,从而产生争用。
-
嗨,我不希望通过并行文件写入来获利,而是通过并行启动外部应用程序来获利
-
创建并行文件仍然可以节省时间:50000 个文件:1 线程 24 秒,4 线程 9 秒,我使用 RAM DISK,而不是 HDD
标签: c++ system openmp stringstream ofstream