    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Const and Concurrency (Part 1)</title>
        <link>https://members.accu.org/index.php/articles/2033</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 26, #5 - November 2014</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c343/">265</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-343/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+343/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Const and Concurrency (Part 1)</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 07 November 2014 15:36:22 +00:00 or Fri, 07 November 2014 15:36:22 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Ralph McArdell comments on comments to Herb Sutterâ€™s updated GotW #6b solution.</p>
<p><strong>Body:</strong>&nbsp;<p>I have been following Herb Sutter on his <em>Sutterâ€™s Mill</em> <a href="#[1]">[1]</a> website and while reading, in 2013, GotW #6b Solution: Const-Correctness, Part 2 <a href="#[2]">[2]</a> and the comments subsequently posted,  some thoughts popped into my head.</p>

<p>For those in need of a reminder or enlightenment, GotW is the commonly used short-form term for Herb Sutterâ€™s â€˜Guru of the Weekâ€™ C++ posers. The â€˜GotW #6b Solution: Const-Correctness, Part 2â€™ article is Herbâ€™s posted solution to the GotW #6b poser which concerns consistent usage of <code>const</code> and <code>mutable</code> in C++ to write safer code. The posed task for which the article provides Herbâ€™s solution is to add or remove <code>const</code> to/from the shown <code>polygon</code> class which caches the result of area calculations, with bonus points awarded if you could point out undefined results or uncompilable code caused by the erroneous use of <code>const</code>. The solution includes concurrency and synchronisation concerns including whether to protect the cached, double, area member by a mutex or make it <code>std::atomic&lt;double&gt;</code> (which is where <code>mutable</code> makes an appearance).</p>

<p>The first comments to catch my eye were about the overhead that may be incurred by <code>std::atomic</code> being only to do with what liberties the compiler can take with respect to optimising writes. This raised an eyebrow as I was under the impression that the need to force atomic operation effects to be globally and consistently visible has more of an effect on performance than reordering write restrictions. Even where a processor has atomic memory update support there is still a cost <a href="#[3]">[3</a>, <a href="#[4]">4]</a> â€“ although that cost is significantly lower in modern processors.</p>

<p>However, the main focus of my thoughts has to do with various comments noting that modifying the set of points added to objects of the problemâ€™s <code>polygon</code> class is not synchronised and performing such changes concurrently with other operations without external synchronisation will end in tears and confusion! One suggestion was to do all the updates on a single thread then allow shared concurrent read access to the finalised polygon. This got me speculating as to how to enforce such a usage pattern, rather than just arrange for violations to such usage to not occur by convention and hope everyone plays along.</p>

<p>What follows is the result of me following up on these initial thoughts, along the lines of â€œletâ€™s see where this goesâ€¦â€, and as such is not intended to necessarily solve any real world problems or even to produce any workable solutions. It is assumed that the types involved, like the GotW 6B <code>polygon</code> class, do not have immutable instances so any thread could potentially modify an instance at any time. If nothing else maybe these musing will serve as an example as to why immutability can be a good thing.</p>

<p>So, the pattern is:</p>

<ol>
	<li>Create an object â€“ e.g. a <code>polygon</code> as per GotW 6b; this occurs on a single thread.</li>
	<li>On this thread perform updates to this object (e.g. add points to the polygon).</li>
	<li>Having performed all updates share the polygon for read-only access from potentially many threads concurrently.</li>
</ol>

<p>The above omits what to do when we wish to delete the object â€“ which of course should be considered a mutating operation! The simplest option might be:</p>

<ol start="4">
	<li>When all threads using the object have died the object may be deleted.</li>
</ol>

<p>Although this seems somewhat restrictive.</p>

<p>During the initial updating phase read-access will, in general, also need to be restricted to access by a single thread. Step 2 could be relaxed to allow access on different threads so long as access only occurred on one thread at a time. It would be nice to relax step 4 to allow the object to be safely deleted without all the reader threads having to terminate first.</p>

<p>Thus mutating and non-mutating (or <code>const</code> in C++ terms) operations have different usage restrictions:</p>

<ul>
	<li>Mutating operations are allowed to be used initially from a single thread then disallowed.</li>
	<li>Non-mutating operations are allowed to be used initially from a single thread then from multiple threads.</li>
</ul>

<p>Letâ€™s consider restricting multithread access first. An obvious lock-based approach would be to create an object in a locked, mutable, state and then change the state to being immutable and release the lock. This does not help with the deletion problem though. Using a readers-writer or readers-upgrade-writer lock could potentially solve this issue: create in mutable, write-locked state, when done setting up the objectâ€™s state move to the immutable readers-locking state, when wanting to destroy the object obtain a writer lock, possibly via an upgrade lock.</p>
<p>Such locking strategies allow for more flexible usage patterns than we require here. Because multithread access is forbidden when in the initial mutable state we can just treat such accesses as errors when in this state. It would be nice to be able to prevent such usage by failing compilation â€“ possibly restricting usage patterns such as use as stack objects only â€“ but (I am fairly certain) this is not attainable. Hence we should look to detecting and raising such misuse as errors at runtime. </p>

<p>One obvious approach would be to use a <code>std::atomic&lt;bool&gt;</code> flag instance member that is tested, set and reset around each mutating operation. An exception is thrown if testing the flag indicates the method is currently being used by some other thread (see Listing 1).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
void the_type::mutating_operation()
{
    bool expect_false {false};
    if (!in_use.compare_exchange_strong(expect_false, true))
    {
        throw std::runtime_error{&quot;!!Concurrent access: illegal usage!!&quot;};
    }
    // Do state changing stuffâ€¦
    in_use = false;
}
</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>This will be monotonous to do repeatedly but the logic could be centralised â€“ for example bundled up into a functor using execute-around to plumb in the boilerplate code around the actual work passed as a lambda function. A rough bare bones implementation might look like Listing 2.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
class enforced_exclusive_executor
{
    std::atomic&lt;bool&gt; in_use;
public:
    enforced_exclusive_executor() : in_use {false}
    {}
    template &lt;class WkFnT&gt;
    void operator()(WkFnT do_work)
    {
        bool expect_false {false};
        if (!in_use.compare_exchange_strong(expect_false, true))
        {
            throw std::runtime_error{&quot;!!Concurrent access: illegal usage!!&quot;};
        }
        do_work();
        in_use = false;
    }
};
</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>Which reduces the mutating operation implementation to:</p>

<pre class="programlisting">
void the_type::mutating_operation()
{
    exclusive_exec([&amp;]()
    {
        /*Do state changing stuffâ€¦*/;
    });
}</pre>

<p>In which<code> exclusive_exec</code> is an instance member of <code>the_type</code> of type <code>enforced_exclusive_executor</code>.</p>

<p>Other than the various overheads incurred this techniqueâ€™s main problem is not necessarily detecting access by multiple threads immediately, if at all. This means that pattern-misuse exceptions are raised indeterminably. Then of course there is the question of what to do about non-mutating operations that do not alter the objectâ€™s state.</p>

<p>A better approach may be to work with a token: if the token matches the current valid token then updates are OK otherwise it is erroneous usage. A convenient token would seem to be a thread id, represented in C++11 by the <code>std::thread::id</code> type (see Listing 3).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
void the_type::mutating_operation()
{
    if (std::this_thread::get_id()!=update_id)
    {
        throw std::runtime_error{&quot;!!Concurrent access: illegal usage!!&quot;};
    }
// Do state changing stuffâ€¦
}
</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p><code>update_id</code> is an instance member of <code>the_type</code> of type <code>std::thread::id</code> which is initialised to the thread id of the thread creating the object. Of course the check logic can be pulled out â€“ for example into a private instance method maybe called something like <code>validate_call_context()</code> (see Listing 4).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
void the_type::validate_call_context()
{
    if (std::this_thread::get_id()!=update_id)
    {
        throw std::runtime_error{&quot;!!Concurrent access: illegal usage!!&quot;};
    }
}
void the_type::mutating_operation()
{
    validate_call_context();
    // Do state changing stuffâ€¦
}
</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<p>This scheme will throw an exception any time any thread other than that the object expected to be called on calls any instance member function that validates its call context â€“ which should be most if not all operations. The scheme has potential to be extended. Transferring the call context to another thread is simply a matter of updating the value of the objectâ€™s <code>update_id</code> to the id of the new calling thread. As such a transfer only makes sense during the initial updating stage of the object, like all such operations during this stage, it would be restricted to being performed only by the current calling context. As a bonus when moving to the shared, immutable state the calling context can be â€˜transferredâ€™ to the single distinct <code>std::thread::id</code> value that does not represent a thread â€“ as produced by default constructing a <code>std::thread::id</code> object â€“ which would ensure that all operations that validate their call context will fail.</p>

<p>A concern is that as <code>std::this_thread_get_id()</code> is called for each validation it should be a cheap â€“ preferably very cheap â€“ operation which may not be the case for all implementations.</p>

<p>I shall pause here and defer developing my musings further for a later article.</p>

<h2>References</h2>

<p class="bibliomixed"><a id="[1]"></a>[1]	<a href="http://herbsutter.com/">http://herbsutter.com/</a></p>

<p class="bibliomixed"><a id="[2]"></a>[2]	http://herbsutter.com/2013/05/28/gotw-6b-solution-const-correctness-part-2/<a id="http://herbsutter.com/2013/05/28/gotw-6b-solution-const-correctness-part-2/"></a>
</p>

<p class="bibliomixed"><a id="[3]"></a>[3]	â€˜Is Parallel Programming Hard, And, If So, What Can You Do About It?â€™ v2013.01.13a especially sections 2.1.3, 2.21, 2.2.3<a href="https://www.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html">https://www.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html</a></p>

<p class="bibliomixed"><a id="[4]"></a>[4]	What Every Programmer Should Know About Memory, section 6.4.2 <a href="http://www.akkadia.org/drepper/cpumemory.pdf">http://www.akkadia.org/drepper/cpumemory.pdf</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
