0
votes

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
Named Pipes were invented for this purpose: IPC - via shared memory - with a handy ReadFile/WriteFile based APIChris Becke

2 Answers

2
votes

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.

0
votes

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.