私はマルチスレッドとC++が初めてで、ファイルを保存するアプリケーションでスレッドを使用しようとすると問題が発生します。コードは以下の通りである:私はこのプログラムを実行するとstringstreamとmultithreading
#include <iostream>
#include <thread>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
void writeCSV(vector<vector<double> > & vec, const char* filename) {
ofstream output(filename);
for (vector<vector<double> >::const_iterator i = vec.begin(); i != vec.end(); ++i) {
for (vector<double>::const_iterator j = i->begin(); j != --i->end(); ++j) {
output << *j << ", ";
}
output << *(--i->end()) << "\n";
}
}
void testFn(int id) {
std::ostringstream filename;
vector<vector<double> > v(460, vector<double>(460,0));
filename << "test" << id << ".csv";
const char* fileStr = filename.str().c_str();
cout << id << " : " << fileStr << endl;
writeCSV(v, fileStr);
}
int main() {
int numOfThreads = 180;
std::thread t[numOfThreads];
for (int i= 0; i< numOfThreads; i++) {
t[i] = std::thread (testFn, i);
}
for (int i = 0; i< numOfThreads; i++) {
t[i].join();
}
return 0;
}
は、それがターミナルに出力します(結果のサブセクション):
66 : 0�c
97 : test97.csv
90 : �'�dz
85 : �'�dz
43 :
9695 : �'�dz
67 : �'�dz
93 :
: �_ ��
115 : test115.csv
144 : test144.csv
99 : test99.c0
68 :
91 : )�
98 : test98.c0
だけでなく、奇妙な/間違ったファイル名でファイルを保存します。これは、私が推測するマルチスレッドとストリームの問題だと思われますが、どのようなアイデアなのか/修正する方法は?
データレースのような音。 –
いいえ、データ競争ではありません。推測はまれに正しい答えにつながります。 –
http://stackoverflow.com/questions/21034834/is-there-issue-will-stringstream-str-c-str – marcinj