Overview
Features
Download
Documentation
Community
Add-Ons & Services

SAMPLE - Activity class, Synchronisation

A general discussion forum.

SAMPLE - Activity class, Synchronisation

Postby bahadir » 15 Dec 2009, 23:55

I'm just trying to write some samples to learn how to use Poco to develop applications. Here is one of them, maybe someone benefit this sample.
This sample demonstrates Activity class and synchronisation using FastMutex. There's a Buffer class(thread-safe) that wraps a stack object and a SizeController class to control the size of a Buffer object. When it determines that the size of buffer is less than the threshold value, it calls Buffer object to load data.
If I have wrongs in the code, I appreciate to hear these. Here's the code:
Code: Select all
#include "Poco/ThreadPool.h"
#include "Poco/Thread.h"
#include "Poco/Runnable.h"
#include "Poco/Mutex.h"
#include "Poco/Random.h"
#include "Poco/Activity.h"
#include <stack>
#include <iostream>

using Poco::Thread;
using Poco::FastMutex;
using Poco::Random;
using Poco::Activity;

#define THRESHOLD 3
#define CHUNKSIZE 5

class Buffer
{
   public:
      Buffer(){}
      int getData()
      {
         int data = 0;
         {
            FastMutex::ScopedLock lock(_mutex);
            data = _elements.top();
            _elements.pop();
         }
         return data;
      }
      void loadData()
      {
         Random rnd;
         {
            FastMutex::ScopedLock lock(_mutex);
            for (int i=0;i<CHUNKSIZE;i++)
               _elements.push(rnd.next(200));
         }
      }
      int size()
      {
         return _elements.size();
      }
   protected:
   private:
      std::stack<int> _elements;
      static FastMutex _mutex;
};
FastMutex Buffer::_mutex;

class SizeController
{
   public:
      SizeController():
         _activity(this, &SizeController::runActivity)
   {
   }

      void setControlObject(Buffer* obj)
      {
         _obj = obj;
      }

      void start()
      {
         _activity.start();
      }

      void stop()
      {
         _activity.stop();
         _activity.wait();
      }

   protected:
      void runActivity()
      {
         while (!_activity.isStopped())
         {
            std::cout<<"--- "<<_obj->size()<<" ---\n";
            if (_obj->size()<THRESHOLD)
            {
               std::cout<<"--- Under Threshold Limit ---\n";
               _obj->loadData();
            }
            Thread::sleep(1000);
         }
      }

   private:
      Activity<SizeController> _activity;
      Buffer* _obj;
};

int main()
{
   Buffer buf;
   buf.loadData();
   SizeController szcontroller;
   szcontroller.setControlObject(&buf);
   szcontroller.start();
   while(1)
   {
      std::cout<<buf.getData()<<"\n"<<std::flush;
      Thread::sleep(5000);
   }
}
bahadir
 
Posts: 17
Joined: 14 Dec 2009, 12:01

Return to General Discussion

Who is online

Users browsing this forum: No registered users and 1 guest