• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
6 #define BOOST_THREAD_USES_MOVE
7 
8 #include <boost/thread/thread.hpp>
9 #include <boost/thread/mutex.hpp>
10 #include <boost/thread/csbl/vector.hpp>
11 #include <iostream>
12 #include <boost/detail/lightweight_test.hpp>
13 #include <boost/static_assert.hpp>
14 
15 int count = 0;
16 boost::mutex mutex;
17 
18 namespace
19 {
20 template <typename TC>
join_all(TC & tc)21 void join_all(TC & tc)
22 {
23   for (typename TC::iterator it = tc.begin(); it != tc.end(); ++it)
24   {
25     it->join();
26   }
27 }
28 
29 template <typename TC>
interrupt_all(TC & tc)30 void interrupt_all(TC & tc)
31 {
32 #if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
33   for (typename TC::iterator it = tc.begin(); it != tc.end(); ++it)
34   {
35     it->interrupt();
36   }
37 #endif
38 }
39 }
40 
increment_count()41 void increment_count()
42 {
43   boost::unique_lock<boost::mutex> lock(mutex);
44   std::cout << "count = " << ++count << std::endl;
45 }
46 
47 #if defined  BOOST_NO_CXX11_RVALUE_REFERENCES && defined BOOST_THREAD_USES_MOVE
48 BOOST_STATIC_ASSERT(::boost::is_function<boost::rv<boost::rv<boost::thread> >&>::value==false);
49 #endif
50 
main()51 int main()
52 {
53   typedef boost::csbl::vector<boost::thread> thread_vector;
54   {
55     thread_vector threads;
56     threads.reserve(10);
57     for (int i = 0; i < 10; ++i)
58     {
59       boost::thread th(&increment_count);
60       threads.push_back(boost::move(th));
61     }
62     join_all(threads);
63   }
64   count = 0;
65   {
66     thread_vector threads;
67     threads.reserve(10);
68     for (int i = 0; i < 10; ++i)
69     {
70       threads.push_back(BOOST_THREAD_MAKE_RV_REF(boost::thread(&increment_count)));
71     }
72     join_all(threads);
73   }
74   count = 0;
75   {
76     thread_vector threads;
77     threads.reserve(10);
78     for (int i = 0; i < 10; ++i)
79     {
80       threads.emplace_back(&increment_count);
81     }
82     join_all(threads);
83   }
84   count = 0;
85   {
86     thread_vector threads;
87     threads.reserve(10);
88     for (int i = 0; i < 10; ++i)
89     {
90       threads.emplace_back(&increment_count);
91     }
92     interrupt_all(threads);
93     join_all(threads);
94   }
95 
96   return boost::report_errors();
97 }
98