Guest User

Untitled

a guest
Nov 12th, 2011
412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2. #include <boost/thread/thread.hpp>
  3. #include <string>
  4. #include <queue>
  5.  
  6. class test
  7. {
  8. public:
  9.     test() : finish(false)
  10.     {
  11.         a = boost::thread(&test::thread_func, this);
  12.     }
  13.     ~test()
  14.     {
  15.         {
  16.             boost::unique_lock<boost::mutex> lk(read_write_queue);
  17.             finish = true;
  18.         }
  19.         new_msgs.notify_one();
  20.     }
  21.     void say(std::string m)
  22.     {
  23.         boost::unique_lock<boost::mutex> lk(read_write_queue);
  24.         msgs.push(m);
  25.         new_msgs.notify_one();
  26.     }
  27. private:
  28.     boost::thread a;
  29.  
  30.     std::queue<std::string> msgs;
  31.     boost::mutex read_write_queue;
  32.     bool finish;
  33.     boost::condition_variable new_msgs;
  34.  
  35.     void thread_func()
  36.     {
  37.         std::string m;
  38.  
  39.         while(true)     // !!!
  40.         {
  41.             { // lock begins
  42.                 boost::unique_lock<boost::mutex> lk(read_write_queue);
  43.                 while(msgs.empty())
  44.                 {
  45.                     new_msgs.wait(lk);
  46.                     if(finish)      // to be called on object destruction
  47.                     {
  48.                         lk.unlock();
  49.                         return;
  50.                     }
  51.                 }
  52.                 m = msgs.front();
  53.                 msgs.pop();
  54.             } // end of lock
  55.             std::cout << m << "\n";     // some processing of data
  56.         }
  57.     }
  58. };
  59.  
  60. int main()
  61. {
  62.     test someone;
  63.     someone.say("cheeze!");
  64.     someone.say("potato!");
  65.     sleep(1);
  66.     return 0;
  67. }
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment