Qt-UI

Producer Consumer Example /w Soup

Queued Connections | | Mandelbrot Example

class Bowl
{
public:

   Bowl() // default constructor
   : empty(true);
   {}

   Bowl(const Bowl &bowl) // copy constructor
   {
      bowl.pour(*this);
   }

   ~Bowl() // destructor
   {}

protected:

   bool empty;

   pour(Bowl &bowl)
   {
      bowl.empty = empty;
      empty = true;
   }

   void put_ingredients()
   {
      empty = false;
   }

   cook_and_stir()
   {
      sleep(5);
   }

public:

   void eat()
   {
      empty = true;
   }

};

class TomKhaGai: public QThread, public Bowl
{
   Q_OBJECT;

public:

   void run()
   {
      wok.lock();

      put_ingredients();
      cook_and_stir();

      Bowl bowl;
      pour(bowl);

      wok.unlock();

      emit done(bowl);
   }

   ~TomKhaGai()
   {
      wait();
   }

protected:

   static QMutex wok;

signals:

   void done(Bowl &bowl);
};

class Guest
{
   Q_OBJECT;

public:

   Guest()
   {
      soup = new TomKhaGai;

      qRegisterMetaType<Bowl>("Bowl");

      connect(soup, SIGNAL(done(Bowl &)),
              this, SLOT(serve(Bowl &)),
              Qt::QueuedConnection);

      soup->start();
   }

   ~Guest()
   {
      delete soup;
   }

protected:

   TomKhaGai *soup;

private slots:

   void serve(Bowl &bowl)
   {
      std::cout << "soup is being served" << std::endl;
      bowl.eat(); // mmh, deliciuos!
   }

};

Usage example:

{
   Guest angela; // soup is being served after 5s
   Guest horst;  // soup is being served after 10s
} // destructor waits 10s


Queued Connections | | Mandelbrot Example

Options: