1

I am taking an operating systems course. I would like to ask about Locks and critical section. Consider the following C function that can be called by multiple threads. I use a lock whenever the shared resource balance is used.

int withdraw(account, amount) 
{
     acquire(lock);
     balance = get_balance(account);
     balance = balance - amount;
     put_balance(account, balance);
     release(lock);
     return balance;
}

My question is should I do it like that or should I release the lock after the return statement? What are the consequences of either way and which of them is a better practice?

I saw another similar Question but it I couldn't understand from it what is the proper thing to do in my example case.

Or b
  • 666
  • 1
  • 5
  • 22
  • 3
    How is the lock supposed to be released if that line is after the return? – Shawn Oct 11 '20 at 12:17
  • Can you post the alternative that you have in mind? – Nikos C. Oct 11 '20 at 12:19
  • @warning the other question use c# and the lock is removed at the end of the {} after it, you you are in C and you need to unlock explicitely – bruno Oct 11 '20 at 12:24
  • @bruno - could you explain why again? i still don't get it – Or b Oct 11 '20 at 13:56
  • @Orb what do you not get ? the fact the lock is automatically cancel in c# ? I see you accepted the answer, it is not enough clear ? – bruno Oct 11 '20 at 14:06

1 Answers1

3

The question you linked to is about C# code, not C. In C#, the lock is automatically released when you return from within a lock block. In C, there is no lock statement. You always need to release it yourself. If you return from within the critical section, the lock will not be released, because none of the statements that come after a return statement will be executed.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96