2

Thinking of a way how to best approach the following design (pseudo C++ code):

class Display {

  public:

   Bitmap GetBitmap(uint16 width, uint16 height);

  private:

   // A list of active bitmaps
   std::set<Bitmap> bitmaps;
}

... where Display is a factory (and sole owner) for Bitmap objects. Display also has to track all the allocated bitmaps within a std::set container and may choose to invalidate/delete them at any time (like in a fullscreen switch).

So essentially a Bitmap is a weak resource handle and whoever holds the handle will have to check if it is valid before using it.

My theoretical solution right now is to use C++ smart pointers:

  • GetBitmap() will return a weak_ptr<Bitmap> and thus can be checked for validity using weakBitmap.lock().
  • Internal bitmaps std::set container will hold shared_ptr<Bitmap> so as to be able to give away weak bitmap pointers.

What is the best way to implement given design? Is there a de facto design pattern for given functionality I am missing?

Sim
  • 2,627
  • 1
  • 20
  • 21
  • 1
    In general, `expired` is not a good way to check for validity. `expired`, as in the name indicates, checks if the pointer is no longer valid. – R. Martinho Fernandes Jan 19 '12 at 12:32
  • But in this case a pointer would be the handle. And if the display decided that this handle is no longer valid and deleted/invalidated it - that should do? Boost docs indicate that `expired()` is the same as `use_count() == 0` so maybe I am missing something. – Sim Jan 19 '12 at 12:40
  • 4
    The problem is that in a multithreaded scenario `if(!x.expired()) assert(x.lock());` may fail. The only reliable information you can obtain from `expired` is that the pointer is "not valid". To get reliable information that the pointer is "valid", you need external guarantees (i.e. there's a single thread, or there's additional synchronization). The correct way to check for pointer validity before use in general is to call `lock`. – R. Martinho Fernandes Jan 19 '12 at 12:44
  • Yep, I am aware of multi-threading issues and the importance of weak pointer `lock()`. I suppose I used `expired` mainly to simplify things. The correct way would be to obtain a `shared_ptr` using a lock() method and if that shared_ptr is empty - assume the resource is expired/invalid. Thanks for the feedback tho! :) – Sim Jan 19 '12 at 15:45

1 Answers1

3

I think you may want to consider turning it around : give away the ownership of objects you have created (e.g. returning boost::shared_ptr<Bitmap>) and only retain weak pointers to objects in your internal collection (e.g. std::list<boost::weak_ptr<Bitmap>>). Whenever user asks for a Bitmap, do a lock on your collection and add a new Bitmap there. If your collection is a list you can safely store iterator to just added element and remove it from the collection later, thus handling destruction of a Bitmap.

Since boost::shared_ptr::lock is atomic, it will also work when multithreading. But you still need to guard access to collection with a lock.

Here is sample code:

#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread.hpp>

class Display;

class Bitmap : boost::noncopyable
{
  friend class Display;
  Bitmap(int, Display* d) : display(d)
  {}

  Display* display;
public:

  ~Bitmap(); // see below for definition
};

typedef boost::shared_ptr<Bitmap> BitmapPtr;

class Display
{
  typedef std::list<boost::weak_ptr<Bitmap>> bitmaps_t;
  typedef std::map<Bitmap*, bitmaps_t::iterator> bitmap_map_t;
  bitmaps_t     bitmaps_;
  bitmap_map_t  bitmap_map_;
  boost::mutex  mutex_;

  friend class Bitmap;
  void Remove(Bitmap* p)
  {
    boost::lock_guard<boost::mutex> g(mutex_);
    bitmap_map_t::iterator i = bitmap_map_.find(p);
    if (i != bitmap_map_.end())
    {
      bitmaps_.erase(i->second);
      bitmap_map_.erase(i);
    }
  }

public:
  ~Display()
  {
    boost::lock_guard<boost::mutex> g(mutex_);
    for (bitmaps_t::iterator i = bitmaps_.begin(); i != bitmaps_.end(); ++i)
    {
      BitmapPtr ptr = i->lock();
      if (ptr)
        ptr->display = NULL;
    }
  }

  BitmapPtr GetBitmap(int i)
  {
    BitmapPtr r(new Bitmap(i, this));
    boost::lock_guard<boost::mutex> g(mutex_);
    bitmaps_.push_back(boost::weak_ptr<Bitmap>(r));
    bitmap_map_[r.get()] = --bitmaps_.end();
    return r;
  }
};

Bitmap::~Bitmap()
{
  if (display)
    display->Remove(this);
}

Please note there is two-way link between Bitmap and Display - they both keep a weak pointer to each other, meaning they can freely communicate. For example, if you want Display to be able to "destroy" Bitmaps, it can simply disable them by updating "display" to NULL, as demonstrated in Display destructor. Display has to lock a weak_ptr<Bitmap> every time it wants to access the Bitmap (example in destructor) but this shouldn't be much of a problem if this communication does not happen often.

For thread safety you may need to lock Bitmap everytime you want to "disable" it i.e. reset display member to NULL, and lock it everytime you want to access "display" from Bitmap. Since this has performance implications, you might want to replace Display* with weak_ptr<Display> in Bitmap. This also removes need for destructor in Display. Here is updated code:

class Bitmap : boost::noncopyable
{
  friend class Display;
  Bitmap(int, const boost::shared_ptr<Display>& d) : display(d)
  {}

  boost::weak_ptr<Display> display;

public:
  ~Bitmap(); // see below for definition
};

typedef boost::shared_ptr<Bitmap> BitmapPtr;

class Display : public boost::enable_shared_from_this<Display>
              , boost::noncopyable
{
  //... no change here

public:
  BitmapPtr GetBitmap(int i)
  {
    BitmapPtr r(new Bitmap(i, shared_from_this()));
    boost::lock_guard<boost::mutex> g(mutex_);
    bitmaps_.push_back(boost::weak_ptr<Bitmap>(r));
    bitmap_map_[r.get()] = --bitmaps_.end();
    return r;
  }
};

Bitmap::~Bitmap()
{
  boost::shared_ptr<Display> d(display);
  if (d)
    d->Remove(this);
}

In this case "disabling" display pointer in Bitmap is thread safe without explicit synchronisation, and looks like this:

Display::DisableBitmap(bitmaps_t::iterator i)
{
  BitmapPtr ptr = i->lock();
  if (ptr)
    ptr->display.reset();
}
bronekk
  • 2,051
  • 1
  • 16
  • 18
  • Thanks, but how would that allow Display to be able to invalidate/delete bitmaps at any time? The problem is that the number of Bitmap users (classes) can grow and is undefined (a Font may need a bitmap and so a UI Label class or others in the future) so the display can't track and send messages to all of them when it's time to invalidate bitmaps. Also, the bitmaps aren't indexed by a key and the factory method is supposed to always create/return a new bitmap (even if requesting the same size). I don't think your answer really solves my issue of Display being the owner of weak resources :) – Sim Jan 19 '12 at 16:12
  • you dont have to use key :) I added sample code to show what I mean. – bronekk Jan 20 '12 at 01:44
  • Can't thank you enough for the sample code, that makes a lot of sense. Upvoted and accepted :) I suppose to check if the bitmap is still valid all you have to do is `if (ptr->display)` on the `shared_ptr` resource. – Sim Jan 20 '12 at 10:49
  • 1
    @Sim Yes indeed, just check "display" member of a Bitmap. May wight want to implement synchronization (mutex, or atomic variable) though if its going to be updated from other thread. It can be further simplified if you have nothing against deriving Display from boost::enable_shared_from_this , as such change would enable Bitmap to simply store weak_ptr. But since you still probably want Display::Remove (to free memory in your collections), it's not as much benefit as it might seem. – bronekk Jan 20 '12 at 10:52
  • That's very detailed, but I am not really worried too much about thread-safety as this is UI code and I do not plan to have it accessed by multiple threads, ever. This should simplify and probably speed up things in my implementation. – Sim Jan 20 '12 at 13:47