1 | // Copyright 2018, 2020 Peter Dimov |
2 | // Distributed under the Boost Software License, Version 1.0. |
3 | // https://www.boost.org/LICENSE_1_0.txt) |
4 | |
5 | #include <boost/shared_ptr.hpp> |
6 | #include <boost/weak_ptr.hpp> |
7 | #include <boost/smart_ptr/detail/lightweight_thread.hpp> |
8 | #include <boost/bind/bind.hpp> |
9 | #include <boost/core/lightweight_test.hpp> |
10 | |
11 | static boost::shared_ptr<int> sp( new int ); |
12 | static boost::weak_ptr<int> wp( sp ); |
13 | |
14 | void f1( int n ) |
15 | { |
16 | for( int i = 0; i < n; ++i ) |
17 | { |
18 | boost::weak_ptr<int> p1( wp ); |
19 | |
20 | BOOST_TEST( !wp.expired() ); |
21 | BOOST_TEST( wp.lock() != 0 ); |
22 | } |
23 | } |
24 | |
25 | void f2( int n ) |
26 | { |
27 | for( int i = 0; i < n; ++i ) |
28 | { |
29 | boost::weak_ptr<int> p1( wp ); |
30 | |
31 | BOOST_TEST( wp.expired() ); |
32 | BOOST_TEST( wp.lock() == 0 ); |
33 | } |
34 | } |
35 | |
36 | int main() |
37 | { |
38 | int const N = 100000; // iterations |
39 | int const M = 8; // threads |
40 | |
41 | boost::detail::lw_thread_t th[ M ] = {}; |
42 | |
43 | for( int i = 0; i < M; ++i ) |
44 | { |
45 | boost::detail::lw_thread_create( th&: th[ i ], f: boost::bind( f: f1, a1: N ) ); |
46 | } |
47 | |
48 | for( int i = 0; i < M; ++i ) |
49 | { |
50 | boost::detail::lw_thread_join( th: th[ i ] ); |
51 | } |
52 | |
53 | BOOST_TEST_EQ( sp.use_count(), 1 ); |
54 | BOOST_TEST_EQ( wp.use_count(), 1 ); |
55 | |
56 | sp.reset(); |
57 | |
58 | BOOST_TEST_EQ( sp.use_count(), 0 ); |
59 | BOOST_TEST_EQ( wp.use_count(), 0 ); |
60 | |
61 | for( int i = 0; i < M; ++i ) |
62 | { |
63 | boost::detail::lw_thread_create( th&: th[ i ], f: boost::bind( f: f2, a1: N ) ); |
64 | } |
65 | |
66 | for( int i = 0; i < M; ++i ) |
67 | { |
68 | boost::detail::lw_thread_join( th: th[ i ] ); |
69 | } |
70 | |
71 | wp.reset(); |
72 | |
73 | return boost::report_errors(); |
74 | } |
75 | |