lockfree: improve building of testsuite
[boost_lockfree.git] / libs / lockfree / test / stack_test.cpp
blob5a3df608f4d14c937614cdcf650b3e78e476b181
1 #include <climits>
2 #define BOOST_TEST_DYN_LINK
3 #define BOOST_TEST_MAIN
4 #include <boost/test/unit_test.hpp>
6 #include "test_helpers.hpp"
8 #include <boost/lockfree/stack.hpp>
10 #include <boost/thread.hpp>
11 #include <iostream>
13 using namespace boost;
14 using namespace std;
16 template <typename freelist_t>
17 struct stack_tester
19 static const unsigned int buckets = 1<<10;
20 static const long node_count = 200000;
21 static const int reader_threads = 4;
22 static const int writer_threads = 4;
24 static_hashed_set<long, buckets> data;
25 boost::array<std::set<long>, buckets> returned;
27 boost::lockfree::detail::atomic<int> push_count, pop_count;
29 boost::lockfree::stack<long, freelist_t> stk;
31 stack_tester(void):
32 push_count(0), pop_count(0)
34 stk.reserve(128);
37 void add_items(void)
39 for (long i = 0; i != node_count; ++i)
41 long id = generate_id<long>();
43 bool inserted = data.insert(id);
44 assert(inserted);
46 while(stk.push(id) == false)
47 thread::yield();
48 ++push_count;
52 boost::atomic<bool> running;
54 void get_items(void)
56 for (;;)
58 long id;
60 bool got = stk.pop(id);
61 if (got)
63 bool erased = data.erase(id);
64 assert(erased);
65 ++pop_count;
67 else
68 if (not running.load())
69 return;
73 void run(void)
75 BOOST_WARN(stk.is_lock_free());
77 running.store(true);
79 thread_group writer;
80 thread_group reader;
82 BOOST_REQUIRE(stk.empty());
84 for (int i = 0; i != reader_threads; ++i)
85 reader.create_thread(boost::bind(&stack_tester::get_items, this));
87 for (int i = 0; i != writer_threads; ++i)
88 writer.create_thread(boost::bind(&stack_tester::add_items, this));
90 using namespace std;
91 cout << "threads created" << endl;
93 writer.join_all();
95 cout << "writer threads joined, waiting for readers" << endl;
97 running = false;
98 reader.join_all();
100 cout << "reader threads joined" << endl;
102 BOOST_REQUIRE_EQUAL(data.count_nodes(), 0);
103 BOOST_REQUIRE(stk.empty());
105 BOOST_REQUIRE_EQUAL(push_count, pop_count);
106 BOOST_REQUIRE_EQUAL(push_count, writer_threads * node_count);
111 BOOST_AUTO_TEST_CASE( stack_test_caching )
113 stack_tester<boost::lockfree::caching_freelist_t> tester;
114 tester.run();
117 BOOST_AUTO_TEST_CASE( stack_test_static )
119 stack_tester<boost::lockfree::static_freelist_t> tester;
120 tester.run();