How to ensure thread-safety
Olly Betts
olly at survex.com
Sun Feb 11 20:51:35 GMT 2018
On Thu, Feb 08, 2018 at 04:18:12PM +0100, Kim Walisch wrote:
> But it is still not clear to me how to ensure thread-safety when using
> libxapian (C++ API). Usually when doing multi-threading many threads can
> read the same variable concurrently without locking provided none of the
> threads modifies the variable.
That's true for simple types, but breaks down for classes because they
may have mutable members - e.g. for caching values computed lazily:
class FactorialFactory {
private:
mutable int r = -1;
mutable int n;
public:
FactorialFactory() {}
int calc(int v) const {
if (r < 0 || n != v) {
r = n;
n = v;
for (int i = n - 1; i > 1; --i) {
r *= i;
}
}
return r;
}
};
It's not safe to concurrently call f.calc() from different threads, even
though conceptually calc() is a read-only method.
Cheers,
Olly
More information about the Xapian-discuss
mailing list