0ad/source/lib/module_init.cpp
janwas cded0936c5 # housekeeping
. update moduleInit mechanism and move it out of lib.cpp. now has a
thread-safe reference count and allows repeated init/shutdown (required
for self-tests)
. vfs now depends on h_mgr; h_mgr need therefore no longer explicitly be
shutdown (e.g. in self-tests)
. acpi: minor fixes
. cpu: AtomicAdd and CAS now take volatile variable (safer)
. mahaf: unload driver on shutdown (did this for DriverVerifier, but
it's 'cleaner' in general)
. wdbg_sym
. wfilesystem: get rid of manual declarations of deprecated functions;
implement them via trampoline instead

This was SVN commit r5086.
2007-05-21 23:24:56 +00:00

75 lines
2.2 KiB
C++

/**
* =========================================================================
* File : module_init.cpp
* Project : 0 A.D.
* Description : helpers for module initialization/shutdown.
* =========================================================================
*/
// license: GPL; see lib/license.txt
#include "precompiled.h"
#include "module_init.h"
#include "lib/sysdep/cpu.h" // cpu_CAS, cpu_AtomicAdd
// notes:
// - value must be 0 to allow users to just define uninitialized static
// variables (they don't have access to our MODULE_* symbols)
// - unlike expected in-game operation, the self-tests require repeated
// sequences of init/shutdown pairs. we therefore allow this in general
// (resetting back to MODULE_UNINITIALIZED after shutdown) because
// there's no real disadvantage other than loss of strictness.
static const ModuleInitState MODULE_UNINITIALIZED = 0u;
// (1..N = reference count)
static const ModuleInitState MODULE_ERROR = ~1u;
bool ModuleShouldInitialize(volatile ModuleInitState* pInitState)
{
// currently uninitialized, so give the green light.
if(cpu_CAS(pInitState, MODULE_UNINITIALIZED, 1))
return true;
// increment reference count - unless already in a final state.
retry:
ModuleInitState latchedInitState = *pInitState;
if(latchedInitState == MODULE_ERROR)
{
debug_warn("attempting to init after error");
return false;
}
if(!cpu_CAS(pInitState, latchedInitState, latchedInitState+1))
goto retry;
return false;
}
bool ModuleShouldShutdown(volatile ModuleInitState* pInitState)
{
// decrement reference count - unless already in a final state.
retry:
ModuleInitState latchedInitState = *pInitState;
if(latchedInitState == MODULE_UNINITIALIZED)
{
debug_warn("shutting down before initialization");
return false;
}
if(latchedInitState == MODULE_ERROR)
return false;
if(!cpu_CAS(pInitState, latchedInitState, latchedInitState-1))
goto retry;
// refcount reached zero => allow shutdown.
if(latchedInitState-1 == MODULE_UNINITIALIZED)
return true;
return false;
}
void ModuleSetError(volatile ModuleInitState* pInitState)
{
*pInitState = MODULE_ERROR;
}