chaeyk
chaeyk

Reputation: 591

c++ function pointer assignment is safe?

Is this code thread safe?

static PFN_SOMEFUNC pfnSomeFunc = nullptr;

PFN_SOMEFUNC SomeFuncGetter();

void CalledFromManyThreads() {
    if (pfnSomeFunc == nullptr)
        pfnSomeFunc = SomeFuncGetter();

    pfnSomeFunc();
}

This is not atomic pointer operation question. There are some special conditions.

Upvotes: 1

Views: 197

Answers (1)

paddy
paddy

Reputation: 63471

It doesn't look thread-safe, because the global variable can be modified by any thread without synchronization. Even an assignment is not guaranteed to be atomic.

What you could do is leverage a language feature that guarantees thread-safe atomic initialization by moving the static into your function (a very common solution to the Static Initialization Fiasco):

void CalledFromManyThreads() {
    static PFN_SOMEFUNC pfnSomeFunc = SomeFuncGetter();
    pfnSomeFunc();
}

Now it's thread-safe. And if you need that cached result in multiple places, you can wrap it:

PFN_SOMEFUNC GetSomeFunc()
{
    static PFN_SOMEFUNC pfnSomeFunc = SomeFuncGetter();
    return pfnSomeFunc;
}

void CalledFromManyThreads() {
    PFN_SOMEFUNC pfnSomeFunc = GetSomeFunc();
    pfnSomeFunc();
}

Upvotes: 3

Related Questions