Document thread safety!

I recently wasted almost an entire day tracking down memory corruption caused by a thread safety issue.  I was working with libMemcached, whose website says right on the front page that the library is thread safe.  Their documentation also says that the library is thread safe.  However, halfway down the page, it says “memcached_st structures are thread-safe, but each thread must contain its own structure” (emphasis mine).  First of all, what does the author think thread safety means, if threads can’t share data?  Second, this whole experience highlighted an important fact: properly documenting thread safety (or lack thereof) is critical.

A responsible developer may verify documentation.  If the docs say that a function returns -1 when passed an invalid argument, the developer can easily just try it out and see.  Thread safety, however, is more difficult.  First of all, even with thread safety, multithreaded programs are not necessarily deterministic, so a simple deterministic test can’t always be written.  Second, thread safety issues may not always be obvious.  A problem may occur in only 1 out of 100 cases, and only when using many threads.  This is why it is vitally important to document thread safety.  Not just whether or not a function (or class, or whatever) is thread safe, but what are the assumptions, and what are the guarantees.  This is always a good idea for any aspect of the code, but it is absolutely necessary for properties (like thread safety) that are difficult to test empirically, and where the developer must rely on the documentation.

One Comment

  1. Posted January 15, 2020 at 8:52 pm | Permalink

    This site was… how do I say it? Relevant!! Finally I have
    found something that helped me. Thank you!

Post a Comment

Your email is never shared. Required fields are marked *