I like the command query separation pattern (from OOSC / Eiffel - basically you either return a value or you change the state of the class - but not both). This makes reasoning about the class easier and it is easier to write exception safe classes.
Now, with multi threading, I run into a major problem: the separation of the query and the command basically invalidates the result from the query as anything can happen between those 2.
So my question is: how do you handle command query separation in an multi-threaded environment?
A stack with command query separation would have the following methods:
- push (command)
- pop (command - but does not return a value)
- top (query - returns the value)
- empty (query)
The problem here is - I can get empty as status, but then I can not rely on top really retrieving an element since between the call of empty and the call of top, the stack might have been emptied. Same goes for pop & top. If I get an item using top, I can not be sure that the item that I pop is the same.
This can be solved using external locks - but that's not exactly what I call threadsafe design.