IAM

OPENSOURCEFAN STUDYING
STUDYINGCOMPUTERSCIENCEANDMATH COMPUTERSCIENCE

Check out the latest superpixel benchmark — Superpixel Benchmark (2016) — and let me know your opinion! @david_stutz
23thJANUARY2017

SNIPPET

C++

Example of implementing parallel accumulate using futures and boost::async for multi-threading.

main.cpp
// http://www.boost.org/doc/libs/1_52_0/doc/html/thread/build.html
#define BOOST_THREAD_PROVIDES_FUTURE

#include <vector>
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/thread/future.hpp>
#include <boost/timer/timer.hpp>

long accumulate(std::vector<int>::iterator begin, std::vector<int>::iterator end)
{
    long accumulated = 0;
    for (std::vector<int>::iterator it = begin; it != end; it++)
    {
        // Artificially adding some more computations ...
        int value = static_cast<double>(*it)/10.;
        accumulated += value;
    }
    
    return accumulated;
}

long parallelAccumulate(std::vector<int>::iterator begin, std::vector<int>::iterator end)
{
    int numBlocks = 10;
    int blockSize = (end - begin) / numBlocks;
    std::vector< boost::future<long> > futures(numBlocks);
    
    for (int i = 0; i < numBlocks; i++)
    {
        std::vector<int>::iterator startBlock = begin + i*blockSize;
        std::vector<int>::iterator endBlock = begin + (i + 1)*blockSize;
        
        if (endBlock >= end)
        {
            endBlock = end;
        }
        
        boost::function<long()> accumulateFunction = boost::bind(accumulate, startBlock, endBlock);
        futures[i] = boost::async(accumulateFunction);
    }
    
    long accumulated = 0;
    for (int i = 0; i < numBlocks; i++)
    {
        accumulated += futures[i].get();
    }
    
    return accumulated;
}

int main()
{
    std::vector<int> vector(100000000);
    for (unsigned int i = 0; i < vector.size(); i++)
    {
        vector[i] = i;
    }
    
    boost::timer::cpu_timer timer;
    long accumulated = accumulate(vector.begin(), vector.end());
    boost::timer::cpu_times elapsed(timer.elapsed());
    
    std::cout << "Single thread: " << std::endl;
    std::cout << boost::timer::format(elapsed, 10, "wall: %w, user; %u, system: %s (%p)") << std::endl;
    std::cout << "Result: " << accumulated << std::endl;
    
    boost::timer::cpu_timer parallelTimer;
    long parallelAccumulated = parallelAccumulate(vector.begin(), vector.end());
    elapsed = boost::timer::cpu_times(parallelTimer.elapsed());
    
    std::cout << "Multi threads: " << std::endl;
    std::cout << boost::timer::format(elapsed, 10, "wall: %w, user; %u, system: %s (%p)") << std::endl;
    std::cout << "Result: " << parallelAccumulated << std::endl;
}

What is your opinion on the code snippet? Is it working? Let me know your thoughts in the comments below or using the following platforms: