views:

273

answers:

2

The following code runs perfectly well on my XP SP2 machine, but the call to WaitForSingleObject waits indefinitely when running on my Vista machine:

HANDLE ghSemaphore;
ghSemaphore = CreateSemaphore(NULL, 0, 1, "COM_PHILOERTEL_FINA");
if (ghSemaphore == NULL) {
 MessageBoxA(NULL,"Error creating semaphore","ERROR",0);
 return FALSE;
}

MessageBoxA(NULL,"Semaphore created. Waiting for it to be triggered","ERROR",0);
WaitForSingleObject(ghSemaphore, INFINITE);
// got the semaphore, ready to rock

MessageBoxA(NULL,"Got the semaphore, ready to rock!","Notice",0);

Here's the thread that releases the semaphore:

 ghSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, "COM_PHILOERTEL_FINA");
 if (ghSemaphore == NULL) {
  MessageBoxA(NULL,"Failed to open semaphore","ERROR",0);
  return FALSE;
 }

 if (0 == ReleaseSemaphore(ghSemaphore, 1, NULL)) {
  MessageBoxA(NULL,"Plugin was unable to release the semaphore","ERROR",0);
  return FALSE;
 }

The named semaphore was a recent addition that didn't do any good. Before that the threads were just sharing ghSemaphore with its anonymous semaphore. No apparent difference. Does anyone have any idea why this binary (compiled on the XP machine in VC6, Express Edition fwiw) wouldn't work in Vista? As I said above, the WaitForSingleObject call is what never finishes.

THanks!

A: 

I cannot check it right now, but heard about it, so try: Change first argument of CreateSemaphore from NULL to empty instance of SECURITY_ATTRIBUTES

SECURITY_ATTRIBUTES dumy;
dumy.nLength = sizeof(dumy);
dumy.lpSecurityDescriptor = 0;
dumy.bInheritHandle = TRUE;
CreateSemaphore(&dumy, 0, 1, "COM_PHILOERTEL_FINA");

By the way named semaphore with lMaximumCount = 1 is fully equivalent of named mutex. So review possibility to use mutex.

Dewfy
Wow, thanks for the quick response! Same behavior with this code added though.
philo
It looks that @Naveen is right, to call ReleaseSemaphore only SEMAPHORE_MODIFY_STATE is needed.
Dewfy
A: 

Solved. This was entirely user error. Thanks @Dewfy, @Naveen, and @avakar for your thoughtful responses.

I was sure the user function was being called because I was displaying its result in my Filemaker layout. What I failed to realize is that these return values are cached by default. The function was never being called. Your suggestions were really helpful, because it wasn't until I fully understood what I was doing with my threads and semaphores that I was able to step back and say "hang on, something's not right here".

I'm still grappling with the mystery of why when I removed the semaphore code I was able to access the resource that the user function was supposed to provide, even though that function was not running. But that's a separate issue.

feels GOOD

philo