Re: How to ensure thread-safety

Olly Betts <[email protected]>
Newsgroups gmane.comp.search.xapian.general
Message-ID <[email protected]>
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
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.