scoped_thread.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. #define BOOST_THREAD_VERSION 3
  7. #include <iostream>
  8. #include <boost/thread/scoped_thread.hpp>
  9. void do_something(int& i)
  10. {
  11. ++i;
  12. }
  13. void f(int, int)
  14. {
  15. }
  16. struct func
  17. {
  18. int& i;
  19. func(int& i_) :
  20. i(i_)
  21. {
  22. }
  23. void operator()()
  24. {
  25. for (unsigned j = 0; j < 1000000; ++j)
  26. {
  27. do_something(i);
  28. }
  29. }
  30. };
  31. void do_something_in_current_thread()
  32. {
  33. }
  34. int main()
  35. {
  36. {
  37. int some_local_state=0;
  38. boost::strict_scoped_thread<> t( (boost::thread(func(some_local_state))));
  39. do_something_in_current_thread();
  40. }
  41. {
  42. int some_local_state=0;
  43. boost::thread t(( func(some_local_state) ));
  44. boost::strict_scoped_thread<> g( (boost::move(t)) );
  45. do_something_in_current_thread();
  46. }
  47. {
  48. int some_local_state=0;
  49. boost::scoped_thread<> t( (boost::thread(func(some_local_state))));
  50. if (t.joinable())
  51. t.join();
  52. else
  53. do_something_in_current_thread();
  54. }
  55. #if 0
  56. {
  57. int some_local_state=0;
  58. boost::thread t(( func(some_local_state) ));
  59. boost::scoped_thread<> g( (boost::move(t)) );
  60. if (g.joinable())
  61. g.detach();
  62. do_something_in_current_thread();
  63. }
  64. #endif
  65. {
  66. boost::scoped_thread<> g( &f, 1, 2 );
  67. do_something_in_current_thread();
  68. }
  69. return 0;
  70. }