My question is how can I ensure that only one thread is using the instance at a particular time.
As a general rule, you can't.
Nathan Oliver's answer works in the special case where the only way for other modules to "use the instance" is by calling it's methods. In that case, you can ensure that every one of those methods locks the same mutex.
But, if your singleton exposes any public
data member, then all bets are off: You will not have any way to control how other modules "use" your object's public data members.
Beware! Even if you make all of the data members private, and make the singleton object really, truly "thread safe;" that still does not guarantee the thread safety of other code that might depend on some relationship between your singleton object and some other data.
Thread safety isn't really about ensuring that "only one thread uses the object at a time." Thread safety is about preserving invariant relationships. For example, if you have a doubly-linked ring data structure, then an important invariant is, p->next->prev
must always be equal to p
.
A thread that wants to splice a new element into the ring must temporarily break the invariant. "Thread safety" in that case means ensuring that no other thread will be able to see the temporarily broken state.
Building a program out of "thread safe" objects doesn't make the whole program "thread safe", because the higher level program can depend on important invariant relationships between the objects. And, even though the objects are individually threads safe, there is no way for them to be aware of the higher-level relationships that are meaningful to the program as a whole.