Main Page Widgets glibmm Namespaces Book

# thread/thread.cc

A glibmm thread example.

    00001
    00002 #include <iostream>
    00003 #include <queue>
    00004 #include <glibmm/random.h>
    00005 #include <glibmm/thread.h>
    00006 #include <glibmm/timer.h>
    00007
    00008
    00009 namespace
    00010 {
    00011
    00012 class MessageQueue : public sigc::trackable
    00013 {
    00014 public:
    00015   MessageQueue();
    00016   ~MessageQueue();
    00017
    00018   void producer();
    00019   void consumer();
    00020
    00021 private:
    00022   Glib::Mutex     mutex_;
    00023   Glib::Cond      cond_push_;
    00024   Glib::Cond      cond_pop_;
    00025   std::queue<int> queue_;
    00026 };
    00027
    00028
    00029 MessageQueue::MessageQueue()
    00030 {}
    00031
    00032 MessageQueue::~MessageQueue()
    00033 {}
    00034
    00035 void MessageQueue::producer()
    00036 {
    00037   Glib::Rand rand (1234);
    00038
    00039   for(int i = 0; i < 200; ++i)
    00040   {
    00041     {
    00042       Glib::Mutex::Lock lock (mutex_);
    00043
    00044       while(queue_.size() >= 64)
    00045         cond_pop_.wait(mutex_);
    00046
    00047       queue_.push(i);
    00048       std::cout << '*';
    00049       std::cout.flush();
    00050
    00051       cond_push_.signal();
    00052     }
    00053
    00054     if(rand.get_bool())
    00055       continue;
    00056
    00057     Glib::usleep(rand.get_int_range(0, 100000));
    00058   }
    00059 }
    00060
    00061 void MessageQueue::consumer()
    00062 {
    00063   Glib::Rand rand (4567);
    00064
    00065   for(;;)
    00066   {
    00067     {
    00068       Glib::Mutex::Lock lock (mutex_);
    00069
    00070       while(queue_.empty())
    00071         cond_push_.wait(mutex_);
    00072
    00073       const int i = queue_.front();
    00074       queue_.pop();
    00075       std::cout << "\x08 \x08";
    00076       std::cout.flush();
    00077
    00078       cond_pop_.signal();
    00079
    00080       if(i >= 199)
    00081         break;
    00082     }
    00083
    00084     if(rand.get_bool())
    00085       continue;
    00086
    00087     Glib::usleep(rand.get_int_range(10000, 200000));
    00088   }
    00089 }
    00090
    00091 }
    00092
    00093
    00094 int main(int, char**)
    00095 {
    00096   Glib::thread_init();
    00097
    00098   MessageQueue queue;
    00099
    00100   Glib::Thread *const producer = Glib::Thread::create(
    00101       sigc::mem_fun(queue, &MessageQueue::producer), true);
    00102
    00103   Glib::Thread *const consumer = Glib::Thread::create(
    00104       sigc::mem_fun(queue, &MessageQueue::consumer), true);
    00105
    00106   producer->join();
    00107   consumer->join();
    00108
    00109   std::cout << std::endl;
    00110
    00111   return 0;
    00112 }
    00113