/* * Copyright (C) 2003-2004 * Slawomir Lisznianski * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Slawomir Lisznianski makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ #include #include #include #include #include /** * We define various task simulators, with different return types; * some will throw exception. */ void doThrowRuntime() { std::cout << "Executing: doThrowRuntime()" << std::endl; throw std::runtime_error("a runtime_error exception"); } int dontThrow(int p) { std::cout << "Executing: dontThrow() with param: " << p << std::endl; return p; } struct A { int fun_a(int a, int b) { return (a+b); } }; std::string greeting() { return "hello, world"; } int main() { try { // Create a scheduler used for queuing tasks. // Rha::BasicScheduler sch; // Define a Futures Registry; list exception types that can be // thrown during task execution. // typedef Rha::FutureRegistry FuRe; /** * Test 1) * Lets start with a simple example. The task will return a * greeting message when "joined" with operator*. */ FuRe::Future f1(sch, greeting); std::cout << "Gretting: " << *f1 << std::endl; /** * Test 2) * This test will schedule two concurrent tasks (f1 and f2), each returning a number. * The returned numbers are then passed as parameters to a third, concurrently * run task - class A member method. */ FuRe::Future f2(sch, boost::bind(dontThrow, 1)); FuRe::Future f3(sch, boost::bind(dontThrow, 2)); A a; FuRe::Future f4(sch, boost::bind(&A::fun_a, a, *f2, *f3)); std::cout << "3 == " << *f4 << std::endl; /** * Test 3) * This test demonstrates usage of Futures with STL containers */ std::vector > v; // Schedule tasks and put Futures into a vector. // for (int i = 0; i < 100; ++i) v.push_back(FuRe::Future(sch, boost::bind(dontThrow, i))); // Print results of each task. // std::transform(v.begin(), v.end(), std::ostream_iterator(std::cout, " "), boost::mem_fn(&FuRe::Future::join)); /** * Test 4) * We finish with a task that will throw an exception. * The exception should be intercepted and re-thrown * when future is joined. */ FuRe::Future f5(sch, doThrowRuntime); f5.join(); } catch (std::exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; } return 0; }