New C++ Concurrency Static Analysis Warnings in Visual Studio 2012
Join the DZone community and get the full member experience.
Join For Freeanother cool feature in the visual studio 2012 c++ compiler is the revamped code analysis rule sets and brand new ui for configuring them. this is not just the simple /analyze switch we all know and love since visual studio 2005 anymore.
to get a general impression of the ui changes, open a c++ project’s properties and check out the code analysis node. you’ll be able to review the rule set that runs on your project and optionally enable/disable specific warnings. check out some of these rules:
specifically, i’d like to focus on the new concurrency analysis rules (in the c261 nn range). these rules—like most c++ code analysis rules—rely on annotations placed in the source code that instruct the analysis engine what to look for. for example, you can place a _guarded_by_(x) annotation on a variable to indicate that access to it should always be protected by a lock x .
carefully placing these annotations all over your source code might seem like an excessive burden, but this is an investment that pays off greatly when you later introduce subtle bugs. consider the following simple example of an account class, whose balance field is protected by the critical section lock :
class account { private: critical_section lock; _guarded_by_(lock) double balance; public: //…constructor and other methods omitted for brevity void withdraw(double amount) { entercriticalsection(&lock); balance –= amount; leavecriticalsection(&lock); } };
sounds easy. now you have a new requirement, to make sure that the balance is not negative before withdrawing. you make the following careless change, and oops—there’s a race condition in your class!
bool withdraw(double amount) { if (balance < 0.0) return false; //oops! entercriticalsection(&lock); balance –= amount; leavecriticalsection(&lock); return true; }
the code analysis engine will detect this problem and report it immediately :
there are many other use cases for these concurrency warnings: mark a variable with _interlocked_ and the compiler will make sure it’s always accessed with an interlocked operation ; failure to release a lock in some code path will always be triggered:
…and there’s the holy grail of deadlock detection, too, if you incorporate lock leveling into your code with the _create_lock_level_, _lock_level_order_ and _has_lock_level_ annotations . here’s an example:
this is definitely a step in the right direction for automatic code analysis in c++. you should at least once try running all the rules on your existing code base—you might be surprised how many nasty bugs code analysis could unveil!
Published at DZone with permission of Sasha Goldshtein, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments