    <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  :: Letter to the Editor</title>
        <link>https://members.accu.org/index.php/journals/1306</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>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #77 - Feb 2007 + Programming Topics + Letters to the Editor</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/journals/">All</a>

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c209/">77</a>
                    (7)
<br />

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

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c186/">LettersEditor</a>
                    (132)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c209-65-186/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c209+65+186/">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;Letter to the Editor</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 31 January 2007 08:30:00 +00:00 or Wed, 31 January 2007 08:30:00 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Alexander Nasonov writes more on singleton.</p>
<p><strong>Body:</strong>&nbsp;<p>Hi Alan,
  </p><p>
    I posted a reference to the Overload 76 to the C++ forum of Russian Software Developer Network (<a href="http://www.rsdn.ru)">http://www.rsdn.ru</a>) and I have had a few replies regarding my article. Since the article has not been reviewed, these comments can be considered as postmortem peer reviews.
  </p><p>
    An anonymous reader replied (translated from Russian):
  </p>
        <p><span class="quote">
    Why did you say nothing about the most popular Meyers singleton where the LOCAL static variable is being used? You showed 2 most awful realizations, which nobody uses (I hope!) and it makes little sense to speak about them. I do not see any advantages of your realization over the Meyers singleton.
  </span></p><p>
    I agree that I should have discussed the Meyers singleton in the article. Single-threaded implementation is very simple and it manages dependencies automatically:
  </p><pre class="programlisting">
 Singleton&amp; instance()
 {
   static Singleton inst;
   return inst;
 }
    </pre><p>
    But it is not so simple in a multithreaded program. Although the C++ standard does not define the term 'thread', my experience says that, if  <tt class="code">main()</tt> is already entered, a thread safety is often guaranteed for static objects at namespace scope but not for local static variables. As a result, the <tt class="code">inst</tt> object may be initialized more than once if two threads call the <tt class="code">instance()</tt> simultaneously.
  </p><p>
    A naive modification of the code above:
  </p><pre class="programlisting">
 mutex mtx;
 Singleton&amp; intance()
 {
   lock l(mtx); // lock mtx now, unlock in dtor
   static Singleton inst;
   return inst;
 }
    </pre><p>
    would break a dependency tracking because now the <tt class="code">instance()</tt> can't be called before the <tt class="code">mtx</tt> is initialized. On POSIX platforms, it can be fixed by using <tt class="code">PTHREAD_MUTEX_INITIALIZER</tt> to initialize the <tt class="code">mtx</tt> object at static phase:
  </p><pre class="programlisting">
 pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
 Singleton&amp; intance()
 {
   lock l(mtx); // lock mtx now, unlock in dtor
   static Singleton inst;
   return inst;
 }
    </pre><p>
    Unfortunately, a static initializer for <tt class="code">CRITICAL_SECTION</tt> is not available on Windows. One has to write a wrapper but it's not a trivial task.
  </p><p>
    This code can be optimized further using double locking technique but you should be very careful. Refer to [DCLocking] from the references section of the article.
  </p><p>
    Another anonymous reader wrote a test program to check a thread safety of the Meyers singleton:
  </p><pre class="programlisting">
 template &lt;typename T&gt;
 class singleton_meyers
 {
 public:
   static T&amp; instance()
   {
     static T obj;
     std::cout &lt;&lt; &quot;instance finished\n&quot; ;;
     return obj;
   }
 };

 struct sleep_in_ctor
 {
   sleep_in_ctor()
   {
     std::cout &lt;&lt; &quot;ctor started\n&quot;;
   ;    sleep(5);
     std::cout &lt;&lt; &quot;ctor finished\n&quot;;
    }
 };

 void stupid_func()
 {
   std::cout &lt;&lt; &quot;stupid func\n&quot;;
   singleton_meyers&lt;sleep_in_ctor&gt; tmp;
   tmp.instance();
 }

 int main()
 {
   boost::thread thrd1(stupid_func);
   boost::thread thrd2(stupid_func);
   thrd1.join();
   thrd2.join();
 }
 </pre><p>
    Before doing thread-safety analysis, I'd like to note that this program uses I/O (<tt class="code">cout</tt>) and process scheduling calls (<tt class="code">sleep</tt>). In general, these calls should be avoided in tests that try to detect race conditions. The output is differ depending on the version of gcc it is compiled with.
    <table border="1" cellspacing="0" cellpadding="5"><tr><td>
      Compiled with gcc 4.1
    </td><td>
    Compiled with gcc 3.4
    </td></tr><tr><td><pre class="programlisting">
 stupid func
   ctor started
   stupid func
     &lt;&lt;&lt; 5 sec pause &gt;&gt;&gt;
   ctor finished
   instance finished
   instance finished
  	</pre></td><td><pre class="programlisting">
 stupid func
   ctor started
   stupid func
   ctor started
     &lt;&lt;&lt; 5 sec pause &gt;&gt;&gt;
   ctor finished
   instance finished
   ctor finished
   instance finished</pre></td></tr></table>
 </p><p>
    As you see, gcc 4.1 correctly initializes the instance while gcc 3.4 incorrectly initializes two instances. Starting from version 4.0, gcc supports one-time construction API: http://www.codesourcery.com/cxx-abi/abi.html#once-ctor.
  </p><p>
    It is on by default but you can disable it with <tt class="code">-fno-threadsafe-statics</tt> option. Note  that it's not a portable extension and you shouldn't rely on it, though it's worth trying it out to detect recursive initialization (refer to 6.7 [stmt.dcl], bullet 4: If control re-enters the declaration (recursively) while the object is being initialized, the behaviour is undefined).
  </p><p>
    To summarize the reviews, I missed one important case which can be used in multithreaded programs if code is written properly, though it may be slower than a solution presented in the article because synchronization is required.
  </p></p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
