[cfe-dev] [libc++] thread safety annotations for unique_lock

christoph@ruediger.engineering via cfe-dev cfe-dev at lists.llvm.org
Thu Nov 10 07:07:02 PST 2016


Am 09.11.16, 20:31 schrieb "Richard Trieu" <rtrieu at google.com>:

>It looks like you are running into the limits of what has been implemented for thread safety analysis.  It doesn't look like SCOPED_CAPABILITY supports unlocking and relocking the mutex.  In these cases, the usual way to use a locking
> class is to do something like:
>
>
>int main(int argc, char const *argv[]) {
>  {
>    unique_lock lock(mtx);
>    any_number = 42;
>  }
>  int i = increment();
>  
>  unique_lock lock(mtx);
>  return i;
>}

Using just a basic lock like std::lock_guard (or the MutexLocker from the documentation), we have to use condition_variable_any instead of condition_variable and hand over the bare mutex instead of std::lock_guard (or the MutexLocker). Just for the sake of completeness, here is how this is supposed to be written, if I understand it right:

// Using the already annotated libc++ here
std::mutex mtx;
std::condition_variable_any cv;

void someFunction() {
  std::lock_guard<std::mutex> lock(mtx);
  while (!active) {
    cv.wait(mtx);
  }
  // Do something...
}

If this is the intended use case, maybe there should be something in the documentation. Because this is what boost and later C++11 have tought the people (Don’t use free mutexes), at least to my understanding. I will add something to the documentation and provide a patch.

I’ve tried to understand the thread safety analysis in clang, but after an hour of looking at the code, this is still a beast and I haven’t found the handle to start off. So from my point of view, there is no short fix available. However, the static analyzer is able to track references of variables, but implementing this into the thread safety analyzer is understanding both of them. I get back to the list with a patch proposal in a year or so... ☺


>The limitations section also says that it doesn't track pointer aliases:
>http://clang.llvm.org/docs/ThreadSafetyAnalysis.html#no-alias-analysis

After re-reading this section, it states clearly that only the example MutexLocker pattern is implemented and nothing else. So my fault, sorry.

Thanks for your help here.

-Christoph



More information about the cfe-dev mailing list