Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Check out <strong>Herb Sutter</strong> talk at <strong>C++ and Beyond 2012</strong>: <a href="http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Herb-Sutter-Concurrency-and-Parallelism" rel="nofollow">C++ Concurrency</a>. He shows example of <a href="http://en.wikipedia.org/wiki/Monitor_%28synchronization%29" rel="nofollow">Monitor Object</a>-like implementation in C++11.</p> <pre><code>monitor&lt;Account&gt; m[2]; transaction([](Account &amp;x,Account &amp;y) { // Both accounts are automaticaly locked at this place. // Do whatever operations you want to do on them. x.money-=100; y.money+=100; },m[0],m[1]); // transaction - is variadic function template, it may accept many accounts </code></pre> <p>Implementation:</p> <p><a href="http://coliru.stacked-crooked.com/a/de69939cf1ec890d" rel="nofollow"><strong>LIVE DEMO</strong></a></p> <pre><code>#include &lt;iostream&gt; #include &lt;utility&gt; #include &lt;ostream&gt; #include &lt;mutex&gt; using namespace std; typedef int Money; struct Account { Money money = 1000; // ... }; template&lt;typename T&gt; T &amp;lvalue(T &amp;&amp;t) { return t; } template&lt;typename T&gt; class monitor { mutable mutex m; mutable T t; public: template&lt;typename F&gt; auto operator()(F f) const -&gt; decltype(f(t)) { return lock_guard&lt;mutex&gt;(m), f(t); } template&lt;typename F,typename ...Ts&gt; friend auto transaction(F f,const monitor&lt;Ts&gt;&amp; ...ms) -&gt; decltype(f(ms.t ...)) { return lock(lvalue(unique_lock&lt;mutex&gt;(ms.m,defer_lock))...), f(ms.t ...); } }; int main() { monitor&lt;Account&gt; m[2]; transaction([](Account &amp;x,Account &amp;y) { x.money-=100; y.money+=100; },m[0],m[1]); for(auto &amp;&amp;t : m) cout &lt;&lt; t([](Account &amp;x){return x.money;}) &lt;&lt; endl; } </code></pre> <p>Output is:</p> <pre><code>900 1100 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload