A C++ technique/library for combining a container and custom logic?

136 views Asked by At

I have a need to occasionally process an object with a delay. The thread that's holding the object cannot delay, however.

A natural solution is to have a separate thread waiting for such objects. When an object becomes available, this second thread would delay as needed and process the object. The second thread would sleep on a semaphore. When the main thread has an object for delayed processing, it would place the object into a queue and signal the semaphore.

While this would work, there's a risk that another programmer (or I) might forget to signal the semaphore upon queuing the object; I want this to be enforced.

So, I might create my own container, which is based on a standard container, but with the addition of a callback (perhaps using policy-based design) and an internal semaphore. It would enforce running the callback function when an item is added to the container.

But this functionality seems so useful and so commonly desired that I would bet that someone has already written this, probably with better design than I am proposing here, and addressed the hairy details such as reentrancy. Does a library for this exist? Or, is there a well-known technique for getting this functionality?

1

There are 1 answers

0
Robᵩ On

I've used private inheritance for this, along with using declarations:

struct myVec : private std::vector<int> {
 // Stuff that works the same
 using std::vector<int>::push_back;
 using std::vector<int>::erase;
 using std::vector<int>::iterator;

 // Stuff that works differently:
 void erase(std::vector<int>::iterator it) { ... }
};

It is important not to use public inheritance from the standard containers. You will end up writing bugs related to slicing and non-virtual destructors.