+ 1
Is my implementation of lock proper?
Hi I implemented singletone pattern for thread also.... Is portion related to thread safety correct ? I am getting only one thread id with this implementation , but the way thread safety is implemented is best or there is some chance of betterment? https://code.sololearn.com/cnIb1K8RRQuL/?ref=app Thanks in advance...!
1 Antwort
+ 6
You should try to avoid locking and unlocking a mutex yourself.
If new throws you'll have a dead lock. ( I know the chances are slim but still )
Instead use std::lock_guard:
https://en.cppreference.com/w/cpp/thread/lock_guard
They are similar to a unique_ptr.
Although do look out for the pitfall where you forget to name the lock_guard, because then your code will no longer be protected by it.
Note that since C++11 local static initialization is thread safe already.
As in
static A& getInstance()
{
static A instance;
return instance;
}
This only applies if the constructor itself is thread safe, though.
I'm not quite sure if it applies in your situation with a static member variable + new.
Also don't forget to mark your copy constructor and assignment operator as deleted.
Apart from that I don't see any other issues.