Misuse of K_GLOBAL_STATIC?
Thiago Macieira
thiago at kde.org
Wed May 14 17:12:46 BST 2008
On Wednesday 14 May 2008 17:53:28 Johannes Sixt wrote:
> Thiago Macieira schrieb:
> > KIMProxy *KIMProxy::instance()
> > {
> > static KIMProxy *self;
> > Q_ONCE
> > self = new KIMProxy;
> > return self;
> > }
> >
> > Unlike the global statics, that ensures the "new" call happens exactly
> > once (unless an exception is thrown). With the global statics, in the
> > event of a reentrancy, the static could be built more than once, even
> > though only one copy will survive.
>
> In the light of this paper:
>
> http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
>
> I'd be interested how Q_ONCE is implemented, in particular, whether it
> uses the Double-Checked-Locking pattern.
>
> [Summary: DCL tries to avoid locking the mutex if the object was already
> allocated. The paper argues that DCL is unsafe because the compiler is
> allowed to rearrange instructions in so many ways.]
#define Q_ONCE_NAME2(prefix, line) prefix ## line
#define Q_ONCE_NAME(prefix, line) Q_ONCE_NAME2(prefix, line)
#define Q_ONCE_INIT(name) \
static QBasicAtomicInt name = Q_BASIC_ATOMIC_INITIALIZER(0)
#define Q_ONCE \
Q_ONCE_INIT(Q_ONCE_NAME(_q_once_, __LINE__)); \
if (0){} else \
for (QOnceControl _control_(Q_ONCE_NAME(_q_once_, __LINE__));
_control_.mustRunCode(); _control_.done())
QOnceControl uses proper memory semantics (testAndSetAcquire,
testAndSetRelease) to enforce the ordering.
QOnceControl::mustRunCode is not inline, so the compiler cannot "guess"
whether it will return true or not. Therefore it can't do anything funky with
the code.
[The Q_ONCE_NAME ugliness is necessary in order to be able to have more than
one Q_ONCE in the same function]
--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
PGP/GPG: 0x6EF45358; fingerprint:
E067 918B B660 DBD1 105C 966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.kde.org/pipermail/kde-core-devel/attachments/20080514/60c72f35/attachment.sig>
More information about the kde-core-devel
mailing list