RAII is quite comfortable and I am having difficulties to provide an equivalent design for resources that must be released in the same order they were acquired (FIFO) as opposed to in the reverse order (Stack) that naturally come out of RAII.
In my specific case, I have a stream class as follow:
template<typename T>
class stream {
...
public:
// Producer API
T& write_acquire(); // This acquires a storage element and will "block"
// until a slot is available in the underlying resource
void write_release(&T); // This releases the storage element, transferring the data to a consumer
// Consumer API
T& read_acquire(); // This acquires a storage element and will "block"
// until a slot has been write_release
void read_release(&T); // This releases the storage element making it available
// for a potential future write_acquire
};
And I was thinking of providing a RAII-style helper:
template<typename T>
class stream_wslot {
stream<T> &s;
T &slot;
public:
stream_wslot(stream<T> &s) : s{s}, slot{s.write_acquire()} {}
~stream_wslot() { s.write_release(slot); }
operator T&() { return slot; }
T& operator=(T &val) { return slot = val; }
};
But the issue is the following usage will not behave correctly:
void test(stream<float> &fifo) {
stream_wslot even(fifo);
stream_wslot odd(fifo);
... first ...
... second ...
// releases odd !!!
// releases even
}
That is, we will release the odd slot before we release the even slot. While I could add a "reordering" queue in the stream I was wondering if there was a "clean" way of generalizing RAII to those situations.