Click here to Skip to main content
15,881,139 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I'm wading through some legacy code and came across the following

HANDLE	hDll;

for (;;) {
    hDll = GetModuleHandle("xxx.dll"); // this is in xxx.dll's source
    if (NULL != hDll) {
         break;
    }
}


I really don't see the point of doing this, and MSDN says nothing about calling it repeatedly. Either it succeeds and loops only once, or fails and loops forever.

Is there any scenario where it is required?

Thanks in advance
Posted
Comments
Mohibur Rashid 22-May-12 5:32am    
Copied from msdn:
Retrieves a module handle for the specified module. The module must have been loaded by the calling process.
I think:
Probably, it wait for the module to be loaded by the same process. may be some other thread is suppose to load the module
Indivara 22-May-12 9:12am    
It is trying to get its own handle, so the thing should definitely be loaded by then.
Mohibur Rashid 22-May-12 22:04pm    
if (NULL != hDll) \\this statement is checking that fact whether it is loaded or not. as I said, it can be loaded by different thread
Indivara 23-May-12 18:56pm    
You mean if two threads call it simultaneously, only one will succeed?
Mohibur Rashid 23-May-12 20:56pm    
take this as example

thread_function(...)
{
while(global_variable);
global_variable=1;
... //rest of code
... //rest of code
global_variable=0;
}

this function will wait to continue until global_variable is set to 0

This looks like a very bad idea. Call it once and report failure/success as required. See also the remarks section here[^].
 
Share this answer
 
v2
Comments
Indivara 22-May-12 9:15am    
That's what I was going to do, but thought there may be some obscure reason for doing this, maybe for some old OS. I really don't want to touch any more than necessary...
Legacy code is fun... ;)
I'll risk a wild guess: someone once used to call LoadLibrary("some_other_library.dll") on a worker thread, and this loop was meant to wait for the other library to be available.
Then, some other person used copy/paste...
Looks like a case of cargo-cult programming[^]

Just my two bits,

Pablo.
 
Share this answer
 
Comments
Indivara 22-May-12 9:16am    
Quite likely. This is from the thousand-liner I mentioned in the Lounge.
C++
#include<windows.h>
#include<stdio.h>
#include<string.h>

int main(void)
{
	HMODULE module_handle = 0;
	while((module_handle = GetModuleHandle(TEXT("library.dll"))) == 0)
		printf("The specified module could not be found.\n");
	printf("Module handle = %x\n", module_handle);
	return 0;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900