• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //  Copyright (C) 2009 Tim Blechmann
2 //
3 //  Distributed under the Boost Software License, Version 1.0. (See
4 //  accompanying file LICENSE_1_0.txt or copy at
5 //  http://www.boost.org/LICENSE_1_0.txt)
6 
7 //[stack_example
8 #include <boost/thread/thread.hpp>
9 #include <boost/lockfree/stack.hpp>
10 #include <iostream>
11 
12 #include <boost/atomic.hpp>
13 
14 boost::atomic_int producer_count(0);
15 boost::atomic_int consumer_count(0);
16 
17 boost::lockfree::stack<int> stack(128);
18 
19 const int iterations = 1000000;
20 const int producer_thread_count = 4;
21 const int consumer_thread_count = 4;
22 
producer(void)23 void producer(void)
24 {
25     for (int i = 0; i != iterations; ++i) {
26         int value = ++producer_count;
27         while (!stack.push(value))
28             ;
29     }
30 }
31 
32 boost::atomic<bool> done (false);
33 
consumer(void)34 void consumer(void)
35 {
36     int value;
37     while (!done) {
38         while (stack.pop(value))
39             ++consumer_count;
40     }
41 
42     while (stack.pop(value))
43         ++consumer_count;
44 }
45 
main(int argc,char * argv[])46 int main(int argc, char* argv[])
47 {
48     using namespace std;
49     cout << "boost::lockfree::stack is ";
50     if (!stack.is_lock_free())
51         cout << "not ";
52     cout << "lockfree" << endl;
53 
54     boost::thread_group producer_threads, consumer_threads;
55 
56     for (int i = 0; i != producer_thread_count; ++i)
57         producer_threads.create_thread(producer);
58 
59     for (int i = 0; i != consumer_thread_count; ++i)
60         consumer_threads.create_thread(consumer);
61 
62     producer_threads.join_all();
63     done = true;
64 
65     consumer_threads.join_all();
66 
67     cout << "produced " << producer_count << " objects." << endl;
68     cout << "consumed " << consumer_count << " objects." << endl;
69 }
70 //]
71