2016-07-17 3 views
0

내가 비동기 적으로 완성 된 각 작업에 대한 콜백을 발생하게 다음 코드 조각 std::vector<std::string> vs에서 파일을 작성하여 부하를 '시뮬레이션'됩니다 작업계정 수를 고려하여 boost :: wait_for_any에서 작업을 올바르게 예약하는 방법은 무엇입니까?

#define BOOST_THREAD_PROVIDES_FUTURE 
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION 

#include <fstream> 
#include <iostream> 
#include <random> 
#include <thread> 
#include <vector> 

#include <boost/thread/future.hpp> 

using vbf = std::vector<boost::future<std::pair<std::string, int>>>; 

void processFile(vbf& v, const std::string& f, int offset) 
{ 
    v.emplace_back(boost::async([offset, &f]() { 
    std::cout << "Starting " << f << '\n'; 
    std::ofstream ofs(f); 
    const int max = offset * 1000000; 
    for (int i = 0; i < max; ++i) ofs << i; 
    // line below wouldn't present the real problem 
    //std::this_thread::sleep_for(std::chrono::milliseconds(max)); 
    return std::make_pair(f, max); 
    })); 
} 

void printProgress(vbf& tasks) 
{ 
    auto it = boost::wait_for_any(tasks.begin(), tasks.end()); 
    while (it != tasks.end()) 
    { 
    const auto res = it->get(); 
    std::cout << "processed file \"" << res.first << "\" with " << res.second << " records\n"; 
    tasks.erase(it); 
    it = boost::wait_for_any(tasks.begin(), tasks.end()); 
    } 
} 

int main() 
{ 
    std::vector<std::string> vs{ 
     "file1", "file2", "file3", "file4", "file5", "file6", "file7", "file8", "file9", 
     "file10", "file11", "file12", "file13", "file14", "file15", "file16", "file17", "file18", 
     "file19", "file20", "file21", "file22", "file23", "file24", "file25", "file26", "file27", 
     "file28", "file29", "file30", "file31", "file32", "file33", "file34", "file35", "file36", 
     "file37", "file38", "file39", "file40", "file41", "file42", "file43", "file44", "file45", 
     "file46", "file47", "file48", "file49", "file50"}; 

    vbf v; 
    v.reserve(vs.size()); 

    std::random_device rd; 
    std::mt19937 gen(rd()); 
    std::uniform_int_distribution<> dis(1, 10); 

    for (const auto& f : vs) processFile(v, f, dis(gen)); 

    printProgress(v); 
} 

의 벡터에 추진해 왔습니다 (코멘트가있다 sleep()와 함께 있지만 CPU에 실제로드가 없기 때문에 이것은 실제 문제를 나타내지 않을 것입니다.

나의 질문은 어떻게 접근 할 수 있습니까?/일정한 접근 방식으로 여기서 일정한 작업을 수행 할 수 있습니다. 그래서 CPU를 통해 '경쟁', 스레드 '싸우지'않습니다.

나는 이것이 사소한 질문이 아니라는 것을 알고 있으며 몇 가지 해결책/접근법 이상의 것이있을 수 있습니다.

온라인 IDE http://melpon.org/wandbox/permlink/aME5cUecefZaBof4

답변

0

가 경합을 방지하려면, 당신이 할 수있는 첫번째 일은 그들을 실행 코어 (하이퍼 스레드)이있는 것보다 시작/(동시에) 더 많은 스레드를 실행하지 않는 것입니다.

+0

그 중 하나가 해결책이 될 수 있지만 어떻게 구체적으로이 접근법으로 해결할 수 있습니까? – Patryk

관련 문제