0
mutex in singleton | is one mutex enough?
Hi Below is my code on singleton pattern for thread safety: https://code.sololearn.com/cnIb1K8RRQuL I heard that single mutex I used to use is not optimized / better solution. Can I know what is more on the mutex side which I am missing in my code. It was related to more than one mutex, but I am not getting it.
5 ответов
+ 2
I don't think the code you commented out can deadlock but lock guards are good practice regardless.
You can't forget to unlock the mutex that way. That's especially true when exceptions are thrown for example.
+ 2
When I answered that I willl use entire method inside mutex lock, the guy was surprised... I mean that case also we won't go into deadlock but was he trying to suggest that rather than having one mutex , are we not gonna on loosing side of the threading?
I might have interpreted him wrong as it was way old video on learning platform... So checking whether can we more optimize with more mutex or it's simply fine to put everything into one mutex for getobjpointer method?
+ 2
I think I see what they are saying.
The mutex should probably go inside the class as a static member, instead of being global. So the mutex is only responsible for that single resource, the singleton object.
(A mutex is just an integer that is `1` if the resource is available and `0` if it's not. One mutex per resource is the right way to go, instead of a global mutex that maybe takes care of many resources.)
In this particular case you can also construct the object before you spawn all the threads, then you don't need mutexes at all.
+ 1
Okay....got it...thanks Schindlabua
+ 1
Found this article perfect for this thread..... Quite interesting so sharing this :
https://www.codeproject.com/Articles/96942/Singleton-Design-Pattern-and-Thread-Safety