stack.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. //[stack_example
  7. #include <boost/thread/thread.hpp>
  8. #include <boost/lockfree/stack.hpp>
  9. #include <iostream>
  10. #include <boost/atomic.hpp>
  11. boost::atomic_int producer_count(0);
  12. boost::atomic_int consumer_count(0);
  13. boost::lockfree::stack<int> stack(128);
  14. const int iterations = 1000000;
  15. const int producer_thread_count = 4;
  16. const int consumer_thread_count = 4;
  17. void producer(void)
  18. {
  19. for (int i = 0; i != iterations; ++i) {
  20. int value = ++producer_count;
  21. while (!stack.push(value))
  22. ;
  23. }
  24. }
  25. boost::atomic<bool> done (false);
  26. void consumer(void)
  27. {
  28. int value;
  29. while (!done) {
  30. while (stack.pop(value))
  31. ++consumer_count;
  32. }
  33. while (stack.pop(value))
  34. ++consumer_count;
  35. }
  36. int main(int argc, char* argv[])
  37. {
  38. using namespace std;
  39. cout << "boost::lockfree::stack is ";
  40. if (!stack.is_lock_free())
  41. cout << "not ";
  42. cout << "lockfree" << endl;
  43. boost::thread_group producer_threads, consumer_threads;
  44. for (int i = 0; i != producer_thread_count; ++i)
  45. producer_threads.create_thread(producer);
  46. for (int i = 0; i != consumer_thread_count; ++i)
  47. consumer_threads.create_thread(consumer);
  48. producer_threads.join_all();
  49. done = true;
  50. consumer_threads.join_all();
  51. cout << "produced " << producer_count << " objects." << endl;
  52. cout << "consumed " << consumer_count << " objects." << endl;
  53. }
  54. //]