Single static initialisation (thread-safe)


#1

I’ve got a library that needs a single initialisation pass. Am I making the right moves here with a SpinLock?

Result setup(const File & libFolder)
{
	static SpinLock lock;

	SpinLock::ScopedLockType l(lock);

	static bool alreadyComplete{ false };

	if (alreadyComplete)
		return Result::ok();

        // initialize some library stuff.

        alreadyComplete = true;
	
	return Result::ok();
}

#2

If you’re happy to lean on the compiler’s built-in function static thread safety, then you could do it without a lock, just using a function-local static whose constructor does the initialisation.

(I think all modern compilers support thread-safe local statics)


#3

void f()
{
static Object object;
//function body
}

object’s constructor is guaranteed to be called once, and will complete before function body is run?


#4

Ah - don’t answer that.

such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. […] If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.