HPA_3_2 - 8BitsCoding/RobotMentor GitHub Wiki

// Ex 1
#include <iostream>
#include <future>
#include <functional>
using namespace std;

int main ( ) {
		packaged_task<int (int, int)>
					addTask ( [] ( int firstInput, int secondInput ) {
 								return firstInput + secondInput;
	});

	future<int> output = addTask.get_future( );

	addTask( 15, 10 );

	cout << "The sum of 15 + 10 is " << output.get() << endl;

	return 0;
}
// Ex 2
#include <iostream>
#include <future>
#include <thread>
using namespace std;

int add ( int firstInput, int secondInput ) {
	return firstInput + secondInput;
}

int main ( ) {

	packaged_task<int (int,int)> addTask( add );

	future<int> output = addTask.get_future();

	thread addThread ( move(addTask), 15, 10);

	addThread.join();

	cout << "The sum of 15 + 10 is " << output.get() << endl;

	return 0;
}
// Ex 3
#include <iostream>
#include <future>
#include <functional>
using namespace std;

int add ( int firstInput, int secondInput ) {
 return firstInput + secondInput;
}

int main ( ) {

 packaged_task<int()> addTask( bind( add, 15, 10));

 future<int> output = addTask.get_future( );

 addTask ( );

 cout << "The sum of 15 + 10 is " << output.get() << endl;
 return 0;
}
// Ex 4
#include <iostream>
#include <future>
#include <climits>
#include <exception>
using namespace std;

void add ( int firstInput, int secondInput, promise<int> output ) {

	try {
         if ( (  INT_MAX == firstInput ) || ( INT_MAX == secondInput ) )
             output.set_exception( current_exception() ) ;
        }
	catch(...) {}

       output.set_value( firstInput + secondInput ) ;

}

int main ( ) {

     try {
	  promise<int> promise_;
    future<int> output = promise_.get_future();
	  async ( launch::deferred, add, INT_MAX, INT_MAX, move(promise_) );
          cout << output.get ( ) << endl;
     }
		 
     catch( exception e ) {
	cerr << "Exception occured" << endl;
     }
}
⚠️ **GitHub.com Fallback** ⚠️