Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <boost/thread/thread.hpp>
- #include <string>
- #include <queue>
- class test
- {
- public:
- test() : finish(false)
- {
- a = boost::thread(&test::thread_func, this);
- }
- ~test()
- {
- {
- boost::unique_lock<boost::mutex> lk(read_write_queue);
- finish = true;
- }
- new_msgs.notify_one();
- }
- void say(std::string m)
- {
- boost::unique_lock<boost::mutex> lk(read_write_queue);
- msgs.push(m);
- new_msgs.notify_one();
- }
- private:
- boost::thread a;
- std::queue<std::string> msgs;
- boost::mutex read_write_queue;
- bool finish;
- boost::condition_variable new_msgs;
- void thread_func()
- {
- std::string m;
- while(true) // !!!
- {
- { // lock begins
- boost::unique_lock<boost::mutex> lk(read_write_queue);
- while(msgs.empty())
- {
- new_msgs.wait(lk);
- if(finish) // to be called on object destruction
- {
- lk.unlock();
- return;
- }
- }
- m = msgs.front();
- msgs.pop();
- } // end of lock
- std::cout << m << "\n"; // some processing of data
- }
- }
- };
- int main()
- {
- test someone;
- someone.say("cheeze!");
- someone.say("potato!");
- sleep(1);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment