Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe container

There is some exemplary class of container in pseudo code:

class Container
{
public:
  Container(){}
  ~Container(){}
  void add(data new)
  {
    // addition of data
  }
  data get(size_t which)
  {
    // returning some data
  }
  void remove(size_t which)
  {
    // delete specified object
  }

private:
  data d;
};

How this container can be made thread safe? I heard about mutexes - where these mutexes should be placed? Should mutex be static for a class or maybe in global scope? What is good library for this task in C++?

like image 901
scdmb Avatar asked Oct 07 '11 07:10

scdmb


1 Answers

First of all mutexes should not be static for a class as long as you going to use more than one instance. There is many cases where you should or shouldn't use use them. So without seeing your code it's hard to say. Just remember, they are used to synchronise access to shared data. So it's wise to place them inside methods that modify or rely on object's state. In your case I would use one mutex to protect whole object and lock all three methods. Like:

class Container
{
public:
  Container(){}
  ~Container(){}
  void add(data new)
  {
    lock_guard<Mutex> lock(mutex);
    // addition of data
  }
  data get(size_t which)
  {
    lock_guard<Mutex> lock(mutex);
    // getting copy of value
    // return that value
  }
  void remove(size_t which)
  {
    lock_guard<Mutex> lock(mutex);
    // delete specified object
  }

private:
  data d;
  Mutex mutex;
};
like image 112
GreenScape Avatar answered Oct 23 '22 21:10

GreenScape