lockfree: improve building of testsuite
[boost_lockfree.git] / libs / lockfree / test / freelist_test.cpp
blobc2cf4bfa0dad6afd7f2b8c23aa95f9224ad0fae9
1 #include <boost/lockfree/detail/freelist.hpp>
2 #include <boost/thread.hpp>
4 #include <climits>
5 #define BOOST_TEST_DYN_LINK
6 #define BOOST_TEST_MAIN
7 #include <boost/test/unit_test.hpp>
9 #include <boost/foreach.hpp>
10 #include <boost/static_assert.hpp>
12 #include <boost/type_traits/is_same.hpp>
14 #include <vector>
17 class dummy
19 int foo[64];
22 template <typename freelist_type>
23 void run_test(void)
25 freelist_type fl(8);
27 std::vector<dummy*> nodes;
29 for (int i = 0; i != 4; ++i)
30 nodes.push_back(fl.allocate());
32 BOOST_FOREACH(dummy * d, nodes)
33 fl.deallocate(d);
35 nodes.clear();
36 for (int i = 0; i != 4; ++i)
37 nodes.push_back(fl.allocate());
39 BOOST_FOREACH(dummy * d, nodes)
40 fl.deallocate(d);
42 for (int i = 0; i != 4; ++i)
43 nodes.push_back(fl.allocate());
46 BOOST_AUTO_TEST_CASE( freelist_tests )
48 run_test<boost::lockfree::detail::freelist_stack<dummy, true> >();
49 run_test<boost::lockfree::detail::freelist_stack<dummy, false> >();
52 template <typename freelist_type>
53 struct freelist_tester
55 static const int max_nodes = 1024;
56 static const int thread_count = 4;
57 static const int loops_per_thread = 1024;
59 boost::lockfree::detail::atomic<int> free_nodes;
60 boost::thread_group threads;
62 freelist_type fl;
64 freelist_tester(void):
65 free_nodes(0), fl(max_nodes * thread_count)
67 for (int i = 0; i != thread_count; ++i)
68 threads.create_thread(boost::bind(&freelist_tester::run, this));
69 threads.join_all();
72 void run(void)
74 std::vector<dummy*> nodes;
75 nodes.reserve(max_nodes);
77 for (int i = 0; i != loops_per_thread; ++i) {
78 while (nodes.size() < max_nodes) {
79 dummy * node = fl.allocate();
80 if (node == NULL)
81 break;
82 nodes.push_back(node);
85 while (!nodes.empty()) {
86 dummy * node = nodes.back();
87 assert(node);
88 nodes.pop_back();
89 fl.deallocate(node);
92 BOOST_REQUIRE(nodes.empty());
96 BOOST_AUTO_TEST_CASE( caching_freelist_test )
98 freelist_tester<boost::lockfree::detail::freelist_stack<dummy, true> > tester();
101 BOOST_AUTO_TEST_CASE( static_freelist_test )
103 freelist_tester<boost::lockfree::detail::freelist_stack<dummy, true> > tester();