std_thread_guard.cpp 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. #include <iostream>
  13. #include <string>
  14. #include <boost/thread/thread_only.hpp>
  15. #include <boost/thread/thread_guard.hpp>
  16. #include <thread>
  17. void do_something(int& i)
  18. {
  19. ++i;
  20. }
  21. struct func
  22. {
  23. int& i;
  24. func(int& i_):i(i_){}
  25. void operator()()
  26. {
  27. for(unsigned j=0;j<1000000;++j)
  28. {
  29. do_something(i);
  30. }
  31. }
  32. private:
  33. func& operator=(func const&);
  34. };
  35. void do_something_in_current_thread()
  36. {}
  37. using thread_guard = boost::thread_guard<boost::join_if_joinable, std::thread>;
  38. void f()
  39. {
  40. int some_local_state;
  41. func my_func(some_local_state);
  42. std::thread t(my_func);
  43. thread_guard g(t);
  44. do_something_in_current_thread();
  45. }
  46. int main()
  47. {
  48. f();
  49. return 0;
  50. }
  51. #endif