thread_vector_pass.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright (C) 2011 Vicente J. Botet Escriba
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #define BOOST_THREAD_USES_MOVE
  6. #include <boost/thread/thread.hpp>
  7. #include <boost/thread/mutex.hpp>
  8. #include <boost/thread/csbl/vector.hpp>
  9. #include <iostream>
  10. #include <boost/detail/lightweight_test.hpp>
  11. #include <boost/static_assert.hpp>
  12. int count = 0;
  13. boost::mutex mutex;
  14. namespace
  15. {
  16. template <typename TC>
  17. void join_all(TC & tc)
  18. {
  19. for (typename TC::iterator it = tc.begin(); it != tc.end(); ++it)
  20. {
  21. it->join();
  22. }
  23. }
  24. template <typename TC>
  25. void interrupt_all(TC & tc)
  26. {
  27. #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
  28. for (typename TC::iterator it = tc.begin(); it != tc.end(); ++it)
  29. {
  30. it->interrupt();
  31. }
  32. #endif
  33. }
  34. }
  35. void increment_count()
  36. {
  37. boost::unique_lock<boost::mutex> lock(mutex);
  38. std::cout << "count = " << ++count << std::endl;
  39. }
  40. #if defined BOOST_NO_CXX11_RVALUE_REFERENCES && defined BOOST_THREAD_USES_MOVE
  41. BOOST_STATIC_ASSERT(::boost::is_function<boost::rv<boost::rv<boost::thread> >&>::value==false);
  42. #endif
  43. int main()
  44. {
  45. typedef boost::csbl::vector<boost::thread> thread_vector;
  46. {
  47. thread_vector threads;
  48. threads.reserve(10);
  49. for (int i = 0; i < 10; ++i)
  50. {
  51. boost::thread th(&increment_count);
  52. threads.push_back(boost::move(th));
  53. }
  54. join_all(threads);
  55. }
  56. count = 0;
  57. {
  58. thread_vector threads;
  59. threads.reserve(10);
  60. for (int i = 0; i < 10; ++i)
  61. {
  62. threads.push_back(BOOST_THREAD_MAKE_RV_REF(boost::thread(&increment_count)));
  63. }
  64. join_all(threads);
  65. }
  66. count = 0;
  67. {
  68. thread_vector threads;
  69. threads.reserve(10);
  70. for (int i = 0; i < 10; ++i)
  71. {
  72. threads.emplace_back(&increment_count);
  73. }
  74. join_all(threads);
  75. }
  76. count = 0;
  77. {
  78. thread_vector threads;
  79. threads.reserve(10);
  80. for (int i = 0; i < 10; ++i)
  81. {
  82. threads.emplace_back(&increment_count);
  83. }
  84. interrupt_all(threads);
  85. join_all(threads);
  86. }
  87. return boost::report_errors();
  88. }