Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Slight alternative to Nim's answer:</p> <p>Create</p> <pre><code>class LockedLog { static MutEx mutex; // global mutex for logging ScopedLock lock; // some scoped locker to hold the mutex Logger &amp;oLogger; // reference to the log writer itself public: LockedLog(Logger &amp;oLogger) : oLogger(oLogger), lock(mutex) {} template &lt;typename T&gt; LockedLog &amp;operator&lt;&lt;(const T &amp;value) { oLogger &lt;&lt; value; return *this; } }; </code></pre> <p>And either just do:</p> <pre><code>LockedLog(oLogger) &lt;&lt; "Log this" &lt;&lt; " and this " &lt;&lt; " and " &lt;&lt; 10 &lt;&lt; endl; </code></pre> <p>Or change <code>Logger::operator&lt;&lt;</code> to normal method, call this method in <code>LockedLog::operator&lt;&lt;</code>, add cast-operator to <code>Logger</code>:</p> <pre><code>operator LockedLog() { return LockedLog(*this); } </code></pre> <p>and that should add locking to your current code.</p> <p><strong>Update:</strong> That locks across all the calls to <code>operator&lt;&lt;</code> and <em>may</em> even lock around evaluation of their arguments (depends on whether compiler will evaluate left or right argument first and it may choose). To reduce that, one could:</p> <pre><code>class LockedLog { static MutEx mutex; // global mutex for logging std::stringstream buffer; // temporary formatting buffer; Logger &amp;oLogger; // reference to the log writer itself public: LockedLog(Logger &amp;oLogger) : oLogger(oLogger), lock(mutex) {} template &lt;typename T&gt; LockedLog &amp;operator&lt;&lt;(const T &amp;value) { buffer &lt;&lt; value; return *this; } ~LockedLog() { ScopedLock lock(mutex); oLogger &lt;&lt; buffer.str() &lt;&lt; std::flush; } }; </code></pre> <p>But the <code>stringstream</code> adds another overhead.</p>
 

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