Re: Confused about a thread-safe singleton example.
Chris M. Thomasson wrote:
"James Kanze" <james.kanze@gmail.com> wrote in message
news:ff9ba37a-3063-4d8c-b848-25dfbc992f5b@w1g2000prm.googlegroups.com...
On Dec 4, 5:45 am, "Chris M. Thomasson" <n...@spam.invalid> wrote:
<jason.cipri...@gmail.com> wrote in message
news:962e1281-0dd3-4571-b941-1de092ff63ed@j32g2000yqn.googlegroups.com...
You can "easily" use `pthread_once()' and compiler specific
directives to construct a fairly "efficient" singleton
pattern;
[...]
I'll admit that I don't see what all the uproar is about. It's
relatively simple to ensure that initialization occurs before
main, so you don't need any locking. And even if you do,
grabbing an uncontended mutex lock just isn't that expensive.
The overhead associated with uncontended locks for frequently accessed
singleton data-structures can be quite significant indeed. For instance,
there can be a #StoreLoad memory order constraint _and_ an atomic RMW
instruction attached to every lock acquisition. Also, there can be a
#LoadStore memory order constraint and atomic RMW along side every lock
release.
Yikes!
Are you concerned about each call to instance() triggering the locking while
only the process of constructing the object actually needs a lock? If so,
what about something like this (of course, FakeLocker would be a real
locker that locks and unlocks a mutex).
#include <iostream>
#include <ostream>
struct Mutex {};
struct FakeLocker {
FakeLocker ( Mutex & ) {
std::cout << "lock\n";
}
~FakeLocker ( void ) {
std::cout << "unlock\n";
}
};
template < typename T >
class once {
struct T_wrapper {
T * ptr;
Mutex the_mutex;
T_wrapper ( void ) {
FakeLocker lock ( the_mutex );
ptr = new T;
}
};
public:
static
T & instance ( void ) {
static T_wrapper dummy;
return ( * dummy.ptr );
}
};
int main ( void ) {
once<int>::instance();
once<int>::instance();
}
Best
Kai-Uwe Bux