开发者

Should I unlock if I call another function inside of a function?

Let's say I have a simple code like this

functionA(){
     lock(l开发者_如何学PythonockA);

     //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.


With current design you could face a deadlock - if some other thread had lockB locked and tries to acquire a lock to lockA both threads are trapped. On the other hand releasing lock to lockA could allow undesired concurrent access to the shared data.

So you have to assess the needs of your program. If you want two threads to access several variables at once (like consistently modify those variables) you should have one lock for all those variables and hold the lock until you've finished access.


Assuming functionB() isn't called from anywhere else, it's safe enough to use just one lock.

Even if you need to use two locks, make sure you release them as soon the work on the shared variable they lock will no longer be used.

With the scenario you have, you may end up into a dead lock if functionB() itself attempted to put a lock on A. Therefore, it's good practice to release locks prior to calling functions that may in turn try to establish a lock.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜