0

I have a basic threading concept question. Is the code after critical section executed even though critical section is waiting to be executed

object myLock = new Object();

Thread1()
{
    lock(myLock)
    {
        //Code1
    }
}

Thread2()
{
    lock(myLock)
    {
        //Code2
    }
    //Code3
}

Say Code1 is executing. I know Code2 won't execute until Code1 is done. But what about Code3, will that wait for Code2 to execute first? thanks

golu
  • 629
  • 2
  • 7
  • 18
  • 1
    Yes. It will "wait" for Code2. I suggest you to read more about type of locking, you can even implement one yourself. – eocron Mar 19 '19 at 18:26
  • Possible duplicate of [How long will a C# lock wait, and what if the code crashes during the lock?](https://stackoverflow.com/questions/6049346/how-long-will-a-c-sharp-lock-wait-and-what-if-the-code-crashes-during-the-lock) – Yauhen Sampir Mar 19 '19 at 18:27
  • I am more curious about Code3. Can it execute before Code2 is executed? – golu Mar 19 '19 at 18:34
  • 2
    Give us some *real code* to reason about, not just comments. I.e. it depends on the nature of `Code2` and `Code3` and whether e.g. `await` or (especially) `ContinueWith` and/or lambdas are also in the picture. In the absence of anything special though, why do you think that `lock` would *break* the sequential nature of code execution? – Damien_The_Unbeliever Mar 19 '19 at 18:36
  • no - why would that make sense. – Daniel A. White Mar 19 '19 at 18:37
  • 2
    Only one of code1 or code2 can be executing at the same time. If Code1 starts first and is still executing, Code2 will wait until Code1 finishes before starting. If Code2 starts before Code1, Code1 will wait until code2 finishes before starting. Once Code2 finishes, Code3 can start (and it doesn't care at all about Code1). Within a single thread, code executes in the normal fashion, roughly from top to bottom - so Code2 will always precede Code3 – Flydog57 Mar 19 '19 at 18:42
  • Thanks, got it. – golu Mar 19 '19 at 18:54
  • 1
    When you ran this code, what happened? Did your tests result in the thread skipping the locked section and running subsequent code, or just waiting until the lock was free? – Servy Mar 19 '19 at 19:06

0 Answers0