Pirx un[blog]ged

Mike is reading four blogs. This is none of them.

Hierarchical Locks

Most rants against C++ are focused on two topics

  • Steep learning curve because the syntax is overly complex.
  • Compile time of template based code takes too long and error messages are virtually useless.

There is also a variation of the first topic: The syntax is utterly confusing to newbies. These arguments are not entirely wrong. But completely wrong are the conclusions. I mean to use Haskell or PHP is not yet a partial solution. But there is a good chance that the compilers and the syntax evolve in a way to fix this problems.

And it would be nice to work with the standard committee to address this problems. But most of us have not a company in the background supporting this. And maybe there is no need to change compilers and syntax. C++ can be completely reshaped by including a library. In some cases this makes sense and is very useful. Boost.Spirit and Streams comes to mind. Nevertheless it's sometimes tempting to enhance the C++ syntax.

After implementing a lock hierarchy as a template based library I thought about possible improvements. There isn't really an obvious limitation, but the syntax wasn't as clean as anticipated. And after a while I had the following syntax in mind:

struct A {
  void foo();   //  write lock
  void bar() const; // read lock
struct B {
  void foo(); // write lock
  lock A a_;

struct C
  lock A a_;
  B b_; // not part of the lock hierarchy
  lock thread_safe ts_;

The keyword lock instructs the compiler to generate the appropriate lock instructions to get a proper lock hierarchy. And the nested struct types represent the object hierarchy in a very natural manner. The compiler must consider three simple rules:

  • A structural change (every non-const function) at one level below, requires a read lock (at the current level)
  • Every const function requires a read lock.
  • Every (read/write) lock escalates as read lock all the way to the top.

Currently I have no idea how to implement this as a library. But I hope to find a solution without the need to write a proposal to the C++ standard committee.

Bonus: But one proposal is overdue. Since lambdas in C++ are everywhere many functions cannot be referenced by name, because they are anonymous. So it's tricky to call a lambda function recursively. It would be nice to have a keyword like self (as an equivalent to this) to address the active function.

comments powered by Disqus