"n"類似のジョブを実行するためにboost :: threadを利用しようとしています。もちろん、一般に "n"は非常に高い可能性があるので、同時に実行しているスレッドの数をいくつかの小さなm(たとえば8)に制限したいと考えています。私は次のようなものを書いています。ここでは、4つのスレッドを使用して一度に4つのテキストファイルを11個開きます。boost :: threadはすべての実行で異なる結果を返します
私は小さなクラスparallel
を持っています(run()
メソッドを呼び出すと、出力ファイルが開き、int変数を取ります)コンパイルはスムーズに進み、プログラムは警告なしで実行されます。 。期待通りではないファイルが作成されますが、それらの数が常に11ではない、誰もが私が作っています間違い何を知ってい
ここparallel.hppう:。?
#include <fstream>
#include <iostream>
#include <boost/thread.hpp>
class parallel{
public:
int m_start;
parallel()
{ }
// member function
void run(int start=2);
};
parallel.cpp実装ファイルは
です#include "parallel.hpp"
void parallel::run(int start){
m_start = start;
std::cout << "I am " << m_start << "! Thread # "
<< boost::this_thread::get_id()
<< " work started!" << std::endl;
std::string fname("test-");
std::ostringstream buffer;
buffer << m_start << ".txt";
fname.append(buffer.str());
std::fstream output;
output.open(fname.c_str(), std::ios::out);
output << "Hi, I am " << m_start << std::endl;
output.close();
std::cout << "Thread # "
<< boost::this_thread::get_id()
<< " work finished!" << std::endl;
}
そして、main.cppに:
#include <iostream>
#include <fstream>
#include <string>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include "parallel.hpp"
int main(int argc, char* argv[]){
std::cout << "main: startup!" << std::endl;
std::cout << boost::thread::hardware_concurrency() << std::endl;
parallel p;
int populationSize(11), concurrency(3);
// define concurrent thread group
std::vector<boost::shared_ptr<boost::thread> > threads;
// population one-by-one
while(populationSize >= 0) {
// concurrent threads
for(int i = 0; i < concurrency; i++){
// create a thread
boost::shared_ptr<boost::thread>
thread(new boost::thread(¶llel::run, &p, populationSize--));
threads.push_back(thread);
}
// run the threads
for(int i =0; i < concurrency; i++)
threads[i]->join();
threads.clear();
}
return 0;
}
本当ですか?作成されたファイルには明確なインデックスがあります。 –
ファイルインデックスとは何か分かりません。ファイルシステムは同じ名前の複数のファイルを許可しないため、ファイルには異なる名前が付いています。 –
no-no ...私のコードでは、 "test - "のbaseNameの後ろにm_startを付加する必要があります... –