Let’s say I have a simple code like this
functionA(){
lock(lockA);
//doing something with a shared data;
functionB();
unLock(lockA);
}
functionB(){
lock(lockB);
//doting something with another shared data
unLock(lockB);
}
I was wondering if I should unlock before I call functionB or it doesn’t matter. Also if I have 2 shared data(A and B) then should I have two mutex lock variables? or can I just use one? Thanks in advance..
If A and B are absolutely not correlated and you won’t do anything else with A after you call function B you should unlock first. There is no need to keep the mutex if you are not going to access A any more.
You should be careful of deadlocks though if you use two lock and do not always obtain them in the same order. Like if you follow your unmodified example locks are acquired on A-B order. If there is a case in your program such that you will acquire locks in B-A order it may cause a deadlock.
You can just use two different locks or a single one depending on the level of granularity you need. Do you mind functions working on A blocks all other functions working on B as well. If that is acceptable for you single lock would be much easier to manage.