Command-Query-Separation and multithreading safe interfaces
Posted
by
Tobias Langner
on Programmers
See other posts from Programmers
or by Tobias Langner
Published on 2012-04-03T08:08:49Z
Indexed on
2012/04/03
11:40 UTC
Read the original article
Hit count: 406
design-patterns
|multithreading
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?
Clarification example:
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.
© Programmers or respective owner