{$MODE OBJFPC}
{$MODESWITCH AUTODEREF}
unit dmutex;

interface

{$ifdef unix}
uses
  cthreads, cmem;
{$endif}

type
PMutex = ^TMutex;
TMutex = object
private
  FCriticalSection: TRTLCriticalSection;
public
  constructor Init;
  destructor Done; virtual;
  procedure Enter; inline;
  procedure Leave; inline;
  // if Mutex.TryEnter then begin
  //   ...
  //   Mutex.Leave;
  // end;
  function TryEnter: Boolean; inline;
end;

implementation

constructor TMutex.Init;
begin
  InitCriticalSection(FCriticalSection);
end;

destructor TMutex.Done;
begin
  DoneCriticalSection(FCriticalSection);
end;

procedure TMutex.Enter;
begin
  EnterCriticalSection(FCriticalSection);
end;

procedure TMutex.Leave;
begin
  LeaveCriticalSection(FCriticalSection);
end;

function TMutex.TryEnter: Boolean;
begin
  Result := TryEnterCriticalsection(FCriticalSection) = 0;
end;

end.
