IAM

OPENSOURCEFAN STUDYING
STUDYINGCOMPUTERSCIENCEANDMATH COMPUTERSCIENCE

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

SNIPPET

C++

An example of using Boost’s implementation of futures and promises for simple 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/atomic.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/future.hpp>
#include <boost/functional.hpp>

int accumulate(const std::vector<int> &vector)
{
    int accumulated = 0;
    for (int i = 0; i < vector.size(); i++)
    {
        accumulated += vector[i];
    }
    
    return accumulated;
}

void accumulateInPromise(const std::vector<int> &vector, 
        boost::promise<int> &promise)
{
    promise.set_value(accumulate(vector));
}

int main()
{
    std::vector<int> vector(100);
    for (int i = 0; i < vector.size(); i++)
    {
        vector[i] = i;
    }
    
    // First variant ...
    boost::promise<int> promise;
    boost::future<int> future1 = promise.get_future();
    boost::function<void()> accumulateFunction1 = boost::bind(accumulateInPromise, vector, std::ref(promise));
    
    boost::thread thread(accumulateFunction1);
    std::cout << future1.get() << std::endl;
    
    // Second variant ...
    boost::function<int()> accumulateFunction2 = boost::bind(accumulate, vector);
    boost::future<int> future2 = boost::async(accumulateFunction2);
    std::cout << future2.get() &lt;&lt; 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: