162

I just realized that in some place in my code I have the return statement inside the lock and sometime outside. Which one is the best?

1)

void example()
{
    lock (mutex)
    {
    //...
    }
    return myData;
}

2)

void example()
{
    lock (mutex)
    {
    //...
    return myData;
    }

}

Which one should I use?

yoozer8
  • 7,361
  • 7
  • 58
  • 93
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341

9 Answers9

215

Essentially, which-ever makes the code simpler. Single point of exit is a nice ideal, but I wouldn't bend the code out of shape just to achieve it... And if the alternative is declaring a local variable (outside the lock), initializing it (inside the lock) and then returning it (outside the lock), then I'd say that a simple "return foo" inside the lock is a lot simpler.

To show the difference in IL, lets code:

static class Program
{
    static void Main() { }

    static readonly object sync = new object();

    static int GetValue() { return 5; }

    static int ReturnInside()
    {
        lock (sync)
        {
            return GetValue();
        }
    }

    static int ReturnOutside()
    {
        int val;
        lock (sync)
        {
            val = GetValue();
        }
        return val;
    }
}

(note that I'd happily argue that ReturnInside is a simpler/cleaner bit of C#)

And look at the IL (release mode etc):

.method private hidebysig static int32 ReturnInside() cil managed
{
    .maxstack 2
    .locals init (
        [0] int32 CS$1$0000,
        [1] object CS$2$0001)
    L_0000: ldsfld object Program::sync
    L_0005: dup 
    L_0006: stloc.1 
    L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)
    L_000c: call int32 Program::GetValue()
    L_0011: stloc.0 
    L_0012: leave.s L_001b
    L_0014: ldloc.1 
    L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)
    L_001a: endfinally 
    L_001b: ldloc.0 
    L_001c: ret 
    .try L_000c to L_0014 finally handler L_0014 to L_001b
} 

method private hidebysig static int32 ReturnOutside() cil managed
{
    .maxstack 2
    .locals init (
        [0] int32 val,
        [1] object CS$2$0000)
    L_0000: ldsfld object Program::sync
    L_0005: dup 
    L_0006: stloc.1 
    L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)
    L_000c: call int32 Program::GetValue()
    L_0011: stloc.0 
    L_0012: leave.s L_001b
    L_0014: ldloc.1 
    L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)
    L_001a: endfinally 
    L_001b: ldloc.0 
    L_001c: ret 
    .try L_000c to L_0014 finally handler L_0014 to L_001b
}

So at the IL level they are [give or take some names] identical (I learnt something ;-p). As such, the only sensible comparison is the (highly subjective) law of local coding style... I prefer ReturnInside for simplicity, but I wouldn't get excited about either.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 16
    I used the (free and excellent) Red Gate's .NET Reflector (was: Lutz Roeder's .NET Reflector), but ILDASM would do too. – Marc Gravell Nov 05 '08 at 21:39
  • 1
    One of the most powerful aspects of Reflector is that you can actually disassemble IL to your preferred language (C#, VB, Delphi, MC++, Chrome, etc) – Marc Gravell Nov 05 '08 at 21:41
  • 3
    For your simple example the IL stays the same, but that is probably because you only return a constant value?! I believe for real life scenarios the result may differ, and parallel threads may cause problems for each other by modifying the value before it's returned it the return statement is outside of the lock block. Dangerous! – Torbjørn Feb 15 '10 at 14:37
  • @MarcGravell: I just came across your post while pondering the same and even after reading your answer, I'm still not sure about the following: Are there ANY circumstances where using the outside approach could break thread-safe logic. I ask this since I prefer a single point of return and don't 'FEEL' good about its thread-safety. Although, if the IL is the same, my concern should be moot anyways. – Raheel Khan Sep 24 '12 at 07:50
  • 1
    @RaheelKhan no, none; they are the same. At the IL level, you **cannot** `ret` inside a `.try` region. – Marc Gravell Sep 24 '12 at 08:07
  • @Torbjørn I think your concerns are valid _but_ only when `Program`, `ReturnInside` and `ReturnOutside` are declared static, otherwise it's safe as `i` would be a local variable then. – ViRuSTriNiTy Nov 19 '15 at 15:25
  • If you return inside the lock, what is returned if the thread waiting to enter the monitor is interrupted? – Alberto Rivelli Mar 04 '16 at 14:55
  • @Alberto again, the point of the IL dump is that **they are identical**; so... *the same thing* – Marc Gravell Mar 04 '16 at 15:01
  • yes sorry I'm not comfortable reading IL, I got the answer from a duplicated question. Thanks anyway – Alberto Rivelli Mar 04 '16 at 15:06
44

It doesn't make any difference; they're both translated to the same thing by the compiler.

To clarify, either is effectively translated to something with the following semantics:

T myData;
Monitor.Enter(mutex)
try
{
    myData= // something
}
finally
{
    Monitor.Exit(mutex);
}

return myData;
Greg Beech
  • 133,383
  • 43
  • 204
  • 250
  • 2
    Well, that is true of the try/finally - however, the return outside the lock still requires extra locals which can't be optimised away - and takes more code... – Marc Gravell Nov 05 '08 at 21:18
  • 3
    You can't return from a try block; it must end with a ".leave" op-code. So the CIL emitted should be the same in either case. – Greg Beech Nov 05 '08 at 21:25
  • 4
    You are right - I've just looked at the IL (see updated post). I learnt something ;-p – Marc Gravell Nov 05 '08 at 21:26
  • 2
    Cool, unfortunately I learned from painful hours trying to emit .ret op-codes in try blocks and having the CLR refuse to load my dynamic methods :-( – Greg Beech Nov 05 '08 at 21:31
  • I can relate; I've done a fair amount of Reflection.Emit, but I'm lazy; unless I'm very sure about something, I write representative code in C# and then look at the IL. But it is surprising how quickly you start thinking in IL terms (i.e. sequencing the stack). – Marc Gravell Nov 05 '08 at 21:44
36

I would definitely put the return inside the lock. Otherwise you risk another thread entering the lock and modifying your variable before the return statement, therefore making the original caller receive a different value than expected.

Sjon
  • 4,989
  • 6
  • 28
  • 46
Ricardo Villamil
  • 5,031
  • 2
  • 30
  • 26
  • 4
    This is correct, a point the other responders seem to be missing. The simple samples they have made may produce the same IL, but this is not so for most real-life scenarios. – Torbjørn Feb 15 '10 at 14:35
  • 5
    Im surprised the other answers dont talk about this – Akshat Agarwal Mar 11 '15 at 18:50
  • 5
    In this sample they are talking about using a stack variable to store the return value, i.e. only the return statement outside the lock and of course the variable declaration. Another thread should have another stack and thus could not make any harm, am I right? – Guillermo Ruffino Feb 29 '16 at 19:47
  • 3
    I don't think this is a valid point, as another thread could update the value between the return call and the actual assignment of the return value to the variable on the main thread. The value being returned can't be changed or or be guaranteed consistency with the current actual value either way. Right? – Uroš Joksimović May 30 '17 at 00:20
  • 1
    This answer is incorrect. Another thread cannot change a local variable. Local variables are stored in the stack, and each thread has its own stack. Btw the default size of a thread's stack is [1 MB](https://stackoverflow.com/questions/28656872/why-is-stack-size-in-c-sharp-exactly-1-mb). – Theodor Zoulias May 27 '20 at 01:06
  • @TheodorZoulias If the local variable contains a _reference_ (a "pointer" to an instance of a reference type), another thread can indeed come in and modify the _referenced object_ after leaving the `lock` block. However, I agree that this ultimately doesn't matter, because if such a referenced object needs protection _when accessed by the caller_, the only way to guarantee that is with a lock on the _caller's_ side - in which case it doesn't matter how many method-internal statements lie between the end of the `lock` block and the `return` statement. – mklement0 May 28 '20 at 02:01
  • This answer tries to make a storm in a teacup. Either way the lock is gone when the return is executed, so if the returned value is a reference type and can be changed by other threads, that is a separate issue. – DasKrümelmonster Jul 15 '23 at 13:46
5

If think the lock outside looks better, but be careful if you end up changing the code to:

return f(...)

If f() needs to be called with the lock held then it obviously needs to be inside the lock, as such keeping returns inside the lock for consistency makes sense.

Rob Walker
  • 46,588
  • 15
  • 99
  • 136
5

It depends,

I am going to go against the grain here. I generally would return inside of the lock.

Usually the variable mydata is a local variable. I am fond of declaring local variables while I initialize them. I rarely have the data to initialize my return value outside of my lock.

So your comparison is actually flawed. While ideally the difference between the two options would be as you had written, which seems to give the nod to case 1, in practice its a little uglier.

void example() { 
    int myData;
    lock (foo) { 
        myData = ...;
    }
    return myData
}

vs.

void example() { 
    lock (foo) {
        return ...;
    }
}

I find case 2 to be considerably easier to read and harder to screw up, especially for short snippets.

Edward Kmett
  • 29,632
  • 7
  • 85
  • 107
2

For what it's worth, the documentation on MSDN has an example of returning from inside of the lock. From the other answers on here, it does appear to be pretty similar IL but, to me, it does seem safer to return from inside the lock because then you don't run the risk of a return variable being overwritten by another thread.

greyseal96
  • 880
  • 7
  • 23
0

To make it easier for fellow developers to read the code I would suggest the first alternative.

Adam Asham
  • 1,519
  • 2
  • 20
  • 32
0

lock() return <expression> statements always:

1) enter lock

2) makes local (thread-safe) store for the value of the specified type,

3) fills the store with the value returned by <expression>,

4) exit lock

5) return the store.

It means that value, returned from lock statement, always "cooked" before return.

Don't worry about lock() return, do not listen to anyone here ))

mshakurov
  • 64
  • 6
-1

Note: I believe this answer to be factually correct and I hope that it is helpful too, but I'm always happy to improve it based on concrete feedback.

To summarize and complement the existing answers:

  • The accepted answer shows that, irrespective of which syntax form you choose in your C# code, in the IL code - and therefore at runtime - the return doesn't happen until after the lock is released.

    • Even though placing the return inside the lock block therefore, strictly speaking, misrepresents the flow of control[1], it is syntactically convenient in that it obviates the need for storing the return value in an aux. local variable (declared outside the block, so that it can be used with a return outside the block) - see Edward KMETT's answer.
  • Separately - and this aspect is incidental to the question, but may still be of interest (Ricardo Villamil's answer tries to address it, but incorrectly, I think) - combining a lock statement with a return statement - i.e., obtaining value to return in a block protected from concurrent access - only meaningfully "protects" the returned value in the caller's scope if it doesn't actually need protecting once obtained, which applies in the following scenarios:

    • If the returned value is an element from a collection that only needs protection in terms of adding and removing elements, not in terms of modifications of the elements themselves and/or ...

    • ... if the value being returned is an instance of a value type or a string.

      • Note that in this case the caller receives a snapshot (copy)[2] of the value - which by the time the caller inspects it may no longer be the current value in the data structure of origin.
    • In any other case, the locking must be performed by the caller, not (just) inside the method.


[1] Theodor Zoulias points out that that is technically also true for placing return inside try, catch, using, if, while, for, ... statements; however, it is the specific purpose of the lock statement that is likely to invite scrutiny of the true control flow, as evidenced by this question having been asked and having received much attention.

[2] Accessing a value-type instance invariably creates a thread-local, on-the-stack copy of it; even though strings are technically reference-type instances, they effectively behave like-value type instances.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Regarding the current state of your answer (revision 13), you are still speculating about the reasons of the existence of the `lock`, and deriving meaning from the placement of the return statement. Which is a discussion unrelated to this question IMHO. Also I find the usage of *"misrepresents"* quite disturbing. If returning from a `lock` misrepresents the flow of control, then the same could be said for returning from a `try`, `catch`, `using`, `if`, `while`, `for`, and any other construct of the language. It's like saying that the C# is riddled with control flow misrepresentations. Jesus... – Theodor Zoulias May 27 '20 at 22:01
  • "It's like saying that the C# is riddled with control flow misrepresentations" - Well, that is technically true, and the term "misrepresentation" is only a value judgment if you choose to take it that way. With `try`, `if`, ... I personally don't tend to even think about it, but in the context of `lock`, specifically, the question arose for me - and if it didn't arise for others too, this question would never have been asked, and the accepted answer wouldn't have gone to great lengths to investigate the true behavior. – mklement0 May 27 '20 at 22:10