std_scoped_thread.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // (C) Copyright 2009-2012 Anthony Williams
  2. // (C) Copyright 2012 Vicente Botet
  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. #if __cplusplus < 201103L
  7. int main()
  8. {
  9. return 0;
  10. }
  11. #else
  12. #define BOOST_THREAD_VERSION 3
  13. #include <iostream>
  14. #include <boost/thread/scoped_thread.hpp>
  15. #include <thread>
  16. #include <cassert>
  17. void do_something(int& i)
  18. {
  19. ++i;
  20. }
  21. void f(int, int)
  22. {
  23. }
  24. struct func
  25. {
  26. int& i;
  27. func(int& i_) :
  28. i(i_)
  29. {
  30. }
  31. void operator()()
  32. {
  33. for (unsigned j = 0; j < 1000000; ++j)
  34. {
  35. do_something(i);
  36. }
  37. }
  38. };
  39. void do_something_in_current_thread()
  40. {
  41. }
  42. using strict_scoped_thread = boost::strict_scoped_thread<boost::join_if_joinable, std::thread>;
  43. using scoped_thread = boost::scoped_thread<boost::join_if_joinable, std::thread>;
  44. int main()
  45. {
  46. {
  47. int some_local_state=0;
  48. strict_scoped_thread t( (std::thread(func(some_local_state))));
  49. do_something_in_current_thread();
  50. }
  51. {
  52. int some_local_state=0;
  53. std::thread t(( func(some_local_state) ));
  54. strict_scoped_thread g( (boost::move(t)) );
  55. do_something_in_current_thread();
  56. }
  57. {
  58. int some_local_state=0;
  59. std::thread t(( func(some_local_state) ));
  60. strict_scoped_thread g( (std::move(t)) );
  61. do_something_in_current_thread();
  62. }
  63. {
  64. int some_local_state=1;
  65. scoped_thread t( (std::thread(func(some_local_state))));
  66. if (t.joinable()) {
  67. t.join();
  68. assert( ! t.joinable() );
  69. }
  70. else
  71. do_something_in_current_thread();
  72. }
  73. #if 0
  74. try
  75. {
  76. int some_local_state=1;
  77. std::thread t(( func(some_local_state) ));
  78. scoped_thread g( (boost::move(t)) );
  79. if (g.joinable()) {
  80. // CLANG crash here
  81. g.detach();
  82. assert( ! g.joinable() );
  83. }
  84. do_something_in_current_thread();
  85. }
  86. catch (...) {
  87. assert( false);
  88. }
  89. #endif
  90. {
  91. scoped_thread g( &f, 1, 2 );
  92. do_something_in_current_thread();
  93. }
  94. return 0;
  95. }
  96. #endif