1 | // Distributed under the Boost Software License, Version 1.0. (See |
---|---|
2 | // accompanying file LICENSE_1_0.txt or copy at |
3 | // http://www.boost.org/LICENSE_1_0.txt) |
4 | // (C) Copyright 2013 Vicente J. Botet Escriba |
5 | |
6 | #define BOOST_THREAD_PROVIDES_INTERRUPTIONS |
7 | |
8 | #include <boost/thread/detail/config.hpp> |
9 | |
10 | #include <boost/thread/thread.hpp> |
11 | #include <boost/thread/completion_latch.hpp> |
12 | |
13 | #include <boost/detail/lightweight_test.hpp> |
14 | #include <vector> |
15 | |
16 | namespace |
17 | { |
18 | |
19 | // Shared variables for generation completion_latch test |
20 | const int N_THREADS = 10; |
21 | boost::completion_latch gen_latch(N_THREADS); |
22 | boost::mutex mutex; |
23 | long global_parameter; |
24 | |
25 | void latch_thread() |
26 | { |
27 | { |
28 | boost::unique_lock<boost::mutex> lock(mutex); |
29 | global_parameter++; |
30 | } |
31 | gen_latch.count_down(); |
32 | //do something else |
33 | } |
34 | |
35 | } // namespace |
36 | |
37 | void test_global_parameter() |
38 | { |
39 | boost::unique_lock<boost::mutex> lock(mutex); |
40 | BOOST_TEST_EQ(global_parameter, N_THREADS); |
41 | } |
42 | |
43 | void reset_gen_latch() |
44 | { |
45 | { |
46 | boost::unique_lock<boost::mutex> lock(mutex); |
47 | BOOST_TEST_EQ(global_parameter, N_THREADS); |
48 | } |
49 | gen_latch.reset(count: N_THREADS); |
50 | } |
51 | |
52 | void test_completion_latch_reset() |
53 | { |
54 | boost::thread_group g; |
55 | boost::thread_group g2; |
56 | |
57 | gen_latch.then(funct: &reset_gen_latch); |
58 | |
59 | { |
60 | global_parameter = 0; |
61 | try |
62 | { |
63 | for (int i = 0; i < N_THREADS; ++i) |
64 | g.create_thread(threadfunc: &latch_thread); |
65 | |
66 | if (!gen_latch.try_wait()) |
67 | if (gen_latch.wait_for(rel_time: boost::chrono::milliseconds(100)) == boost::cv_status::timeout) |
68 | if (gen_latch.wait_until(abs_time: boost::chrono::steady_clock::now()+boost::chrono::milliseconds(100)) == boost::cv_status::timeout) |
69 | gen_latch.wait(); // All the threads have been updated the global_parameter |
70 | g.join_all(); |
71 | } |
72 | catch (...) |
73 | { |
74 | BOOST_TEST(false); |
75 | g.interrupt_all(); |
76 | g.join_all(); |
77 | //throw; |
78 | } |
79 | } |
80 | gen_latch.then(funct: &test_global_parameter); |
81 | { |
82 | global_parameter = 0; |
83 | try |
84 | { |
85 | for (int i = 0; i < N_THREADS; ++i) |
86 | g2.create_thread(threadfunc: &latch_thread); |
87 | |
88 | if (!gen_latch.try_wait()) |
89 | gen_latch.wait(); // All the threads have been updated the global_parameter |
90 | |
91 | g2.join_all(); |
92 | } |
93 | catch (...) |
94 | { |
95 | BOOST_TEST(false); |
96 | g2.interrupt_all(); |
97 | g2.join_all(); |
98 | //throw; |
99 | } |
100 | } |
101 | } |
102 | |
103 | int main() |
104 | { |
105 | test_completion_latch_reset(); |
106 | return boost::report_errors(); |
107 | } |
108 | |
109 |