Re: code pattern for locking & unlocking
On 27.11.2010 01:22, Goran wrote:
On Nov 25, 11:48 pm, Daniel Anderson<woni...@gmail.com> wrote:
[...]
I don't know of a better way than what you've shown, and I don't
consider hanging blocks bad. If you are so bothered, there is nothing
wrong in creating a function specifically for your block. Imagine:
void SynchronizedPart(type1& p1, type2& p2, type3& p3)
{
lock l(mutex);
abuse(p1, p2, p3);
}
void someFunc()
{
// do stuff...
SynchronizedPart(d1, d2, d3);
// do more stuff
}
This arguably even reads better and you can be pretty sure that you'll
normally get no runtime overhead whatsoever (optimization will see
that there's only one use of SynchronizedPart and will inline it).
PLEASE, can we stop this whole ""no runtime overhead whatsoever (optimization
will see"" stuff? The optimizer is far more limited (some might call it stupid)
than such blanket statements admit.
For example, in the above snippet, unless SynchronizedPart is marked as static
or enclosed in an anonymous namespace, the compiler/optimizer should assume
external linkage and as such will treat this function no differently than any
other function, no matter how often it's used.
Oh wait, you could also mark it as inline, except, to quote one arguably popular
compilers[1] docs:
The inline keyword tells the compiler
that inline expansion is preferred.
However, the compiler can create a separate
instance of the function (instantiate) and
create standard calling linkages instead
of inserting the code inline.
And [2],
In some cases, the compiler will not inline
a particular function for mechanical reasons.
For example, the compiler will not inline:
* A function if it would result in mixing
both SEH and C++ EH.
* Some functions with copy constructed
objects passed by value[...]
* Functions returning an unwindable
object by value[...]
* [...]
* A function with a try (C++ exception handling) statement.
So if your fn is containing a simple innocent try block, MS VC++ ain't ever able
to inline it! If SynchronizedPart happens to return a non-void non-trivial
object by value: no inlining!
NOTE - this reply is not intended to imply that a user should overmuch care
about these inlining *details*, nor should it imply that the use of a separate
function should be avoided!
Its point is rather to point out that peppering our replys with "trust your
optimizer" statements is by no means always appropriate.
cheers,
Martin
[1] MS VC++ 2010 inline keywords :
http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx
[2] Compiler Warning (level 4) C4714 :
http://msdn.microsoft.com/en-us/library/a98sb923%28v=VS.100%29.aspx
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]