I am writing some code to perform explicit linking to a DLL. This code is offered to my users as an alternative to implicit linking with a .lib file. At the moment my planned code looks like this:
void DisableModule(int Module)
{
typedef void (*DisableModuleProc)(int);
static DisableModuleProc proc = NULL;
if (proc == NULL)
proc = (DisableModuleProc)GetProcAddress(hModule, "DisableModule");
proc(Module);
}
There are lots of functions of this form, and I have excised the error checking for the purpose of this question.
My problem concerns thread safety. This function could potentially be called simultaneously from multiple threads. Clearly there is a race on the static variable _DisableModule. My belief is that because _DisableModule will be aligned on machine word boundary (either 32 or 64 bit boundary depending on target), that no tearing can occur and so the race is benign. It’s possible that GetProcAddress will be called more times than necessary, but I do not believe that affects correctness of the program.
Is my analysis correct?
This code is perfectly safe on x86 and amd64.
At worst
GetProcAddressis called several times.On other architectures there may be problems with partial writes being interrupted. To circumvent this, you could use atomics (
InterlockedComparExchange…), but this is superfluous here.