views:

318

answers:

2

I am creating an application that implements inter process communication. For this purpose I have set up a shared buffer, which seems to work fine. Now, I need a way for the data generating application (written in c++) to tell the data receiving application (written in freepascal/lazarus) when it should read the data.

I was trying to use a mutex for this purpose. I do not have much experience with windows api programming.

So, my problem is, in the FreePascal code below, the mutex won't wait. I can call the TMutex.Wait() function, it doesn't return an error or anything, but it simply won't wait.

constructor TMutex.Create(sName: AnsiString);
begin
  sName := 'Local\Mutex'+sName;
  hMutex := CreateMutexA(
        nil, // default access
        True, // initially not owned
        PChar(sName)); // named mutex
  if hMutex = 0 then
  begin
    raise Exception.Create('mutex creation failed');
  end;
end;

destructor TMutex.Destroy;
begin
  CloseHandle(hMutex);
end;

procedure TMutex.Wait;
begin
  if (WaitForSingleObject(hMutex, INFINITE) <> 0) then ShowMessage('debug: wait returned something');
end;

procedure TMutex.Post;
begin
  ReleaseMutex(hMutex);
end;

+2  A: 

It looks like your problem is at:

    True, // initially not owned

You have things backwards -- true means it initially IS owned, so waiting on it will return immediately.

Jerry Coffin
tried both true and false, doesn't seem to make a difference. I had it origially false, changed it to true to see if that changed anything but didn't update the comment. Since it didn't change anything, I started to look elsewhere and forgot about that. Still, setting ti back to false doesn't change anything.
andremo
A: 

you don't show us the code that calls the Wait, method of TMutex. however, you have to know that a mutex is reentrant: if a thread owns a mutex, it will always be granted access to it, thus a wait will never block. this is built into the mutex to avoid deadlocks.

try acquiring the mutex from another thread, the wait should block.

Adrien Plisson
thanks, I will try this. I'll tell if it works later.
andremo
Okay, now I gotuses sharedmem;procedure TIPCThread.test ;begin ShowMessage('blaat')end;procedure TIPCThread.Execute;begin Synchronize(@Test); BlaatSharedMem.Mutex.Wait; Synchronize(@Test);end;Still.... I got two ShowMessages with no wait between them. I did start a new thread here as you see, in which I do the waiting, but no difference, it doesn´t wait at all.
andremo