title: Generic Components Friendly To Software Transactional Memory
body: <p>Say we write some new class which can be used concurrently or not. Obviously, we don't want to have locks on everything on the chance that they will be called concurrently. One way to address this is through parameterizing by <a href="http://www.drdobbs.com/cpp/mixin-based-programming-in-c/184404445" rel="nofollow">mixins</a> specifying locking:</p>
  
  <pre><code>template&lt;class Locking&gt;
  struct foo : private Locking {
      void bar() {
          Locking::read_lock();
          // Do something.
          Locking::read_unlock();
      }
  };
  </code></pre>
  
  <p>and instantiating <code>Locking</code> with a class that actually locks for the multithreading case, and with a class that does no-ops for the other case (hopefully, the compiler will even optimize away the calls).</p>
  
  <p>Now suppose I'd like to do this with software-transactional memory instead of locking. Looking at <a href="https://isocpp.org/files/papers/N3919.pdf" rel="nofollow">N3919</a> (or the <a href="https://gcc.gnu.org/wiki/TransactionalMemory" rel="nofollow">gcc precursor</a>), the idea is different. There are no calls such as</p>
  
  <pre><code>transaction_start();
  
  transaction_end();
  </code></pre>
  
  <p>Instead there are function specifiers like</p>
  
  <pre><code>void bar() transaction_safe;
  </code></pre>
  
  <p>and block specifiers like</p>
  
  <pre><code>transaction { /* body */ }
  </code></pre>
  
  <p>with strict rules of the latter calling the former, and nothing that looks like it can be used by mixins.</p>
  
  <p>How can this be done(<em>without</em> involving the preprocessor)? Note also that <a href="https://en.wikipedia.org/wiki/Software_transactional_memory#Composable_operations" rel="nofollow">one of the main benefits of STM is composability</a>, but there seems no way to get the instantiation to reflect that <code>bar</code> is transactionable.</p>