spsc_queue.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. //[spsc_queue_example
  7. #include <boost/thread/thread.hpp>
  8. #include <boost/lockfree/spsc_queue.hpp>
  9. #include <iostream>
  10. #include <boost/atomic.hpp>
  11. int producer_count = 0;
  12. boost::atomic_int consumer_count (0);
  13. boost::lockfree::spsc_queue<int, boost::lockfree::capacity<1024> > spsc_queue;
  14. const int iterations = 10000000;
  15. void producer(void)
  16. {
  17. for (int i = 0; i != iterations; ++i) {
  18. int value = ++producer_count;
  19. while (!spsc_queue.push(value))
  20. ;
  21. }
  22. }
  23. boost::atomic<bool> done (false);
  24. void consumer(void)
  25. {
  26. int value;
  27. while (!done) {
  28. while (spsc_queue.pop(value))
  29. ++consumer_count;
  30. }
  31. while (spsc_queue.pop(value))
  32. ++consumer_count;
  33. }
  34. int main(int argc, char* argv[])
  35. {
  36. using namespace std;
  37. cout << "boost::lockfree::queue is ";
  38. if (!spsc_queue.is_lock_free())
  39. cout << "not ";
  40. cout << "lockfree" << endl;
  41. boost::thread producer_thread(producer);
  42. boost::thread consumer_thread(consumer);
  43. producer_thread.join();
  44. done = true;
  45. consumer_thread.join();
  46. cout << "produced " << producer_count << " objects." << endl;
  47. cout << "consumed " << consumer_count << " objects." << endl;
  48. }
  49. //]