factorial3.cpp 862 B

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright (C) 2001-2003
  2. // William E. Kempf
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #include <boost/thread/thread.hpp>
  7. #include <iostream>
  8. const int NUM_CALCS=5;
  9. class factorial
  10. {
  11. public:
  12. factorial(int x, int& res) : x(x), res(res) { }
  13. void operator()() { res = calculate(x); }
  14. int result() const { return res; }
  15. private:
  16. int calculate(int x) { return x <= 1 ? 1 : x * calculate(x-1); }
  17. private:
  18. int x;
  19. int& res;
  20. };
  21. int main()
  22. {
  23. int results[NUM_CALCS];
  24. boost::thread_group thrds;
  25. for (int i=0; i < NUM_CALCS; ++i)
  26. thrds.create_thread(factorial(i*10, results[i]));
  27. thrds.join_all();
  28. for (int j=0; j < NUM_CALCS; ++j)
  29. std::cout << j*10 << "! = " << results[j] << std::endl;
  30. }