私はboost::threadを利用して「n」個の同様のジョブを実行しようとしています。もちろん、一般に「n」は非常に高くなる可能性があるため、同時に実行されるスレッドの数をいくつかの小さな数m(たとえば8)に制限したいと思います。私は次のようなものを書きました。ここでは、4つのスレッドを使用して一度に4つのテキストファイルを11個開きます。
私は小さなクラスを持って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;
}