Fastream Technologies wrote:
> Hello,
> 
> So this is my latest code:
> 
> void inline __fastcall lockCriticalSection(TCriticalSection
> *criticalSection) {
> for(int i = 0; i < 5000; ++i)
> {
> if(criticalSection->TryEnter())
> return;

Calling Sleep() in such short intervals is critical.
With each call to Sleep() you force a context switch, this will
slow down entire application and may lead to strange results.

Try something like the class below (untested), copy the code
to a new file, name it MySyncObjs.pas and replace SyncObjs by
MySyncObjs in your uses clause (works only if you do not use
other objects from that unit as well). I use MadExept 2.7.

--------------------------------------------------------------
unit MySyncObjs;

interface

uses
  Windows, Sysutils, MadExcept;

type
  ECriticalSection = class(Exception);
  TCriticalSection = class(TObject)
  protected
    FMutex : THandle;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Acquire;
    procedure Release;
    procedure Enter;
    procedure Leave;
  end;

implementation

{ TCriticalSection }

constructor TCriticalSection.Create;
begin
    FMutex := CreateMutex(nil, FALSE, nil);
    if FMutex = 0 then
      ECriticalSection.Create(SysErrorMessage(GetLastError));
end;

destructor TCriticalSection.Destroy;
begin
  if FMutex <> 0 then
      CloseHandle(FMutex);
  inherited;
end;

procedure TCriticalSection.Acquire;
begin
    Enter
end;

procedure TCriticalSection.Enter;
var
  WaitResult: Cardinal;
begin  
  try
    WaitResult := WaitForSingleObject(FMutex, 5000);
    case WaitResult of
      WAIT_TIMEOUT :  raise ECriticalSection.Create('Critical Section timed 
out');
      WAIT_ABANDONED: raise ECriticalSection.Create('Critical Section 
abandoned');
      WAIT_FAILED: raise ECriticalSection.Create(SysErrorMessage(GetLastError));
    end;
  except
    MadExcept.HandleException;
  end;
end;

procedure TCriticalSection.Leave;
begin
    Release
end;

procedure TCriticalSection.Release;
begin
    if not ReleaseMutex(FMutex) then
        ECriticalSection.Create(SysErrorMessage(GetLastError));
end;

end.


--------------------------------------------------------------

--
Arno Garrels [TeamICS]
http://www.overbyte.be/eng/overbyte/teamics.html
-- 
To unsubscribe or change your settings for TWSocket mailing list
please goto http://www.elists.org/mailman/listinfo/twsocket
Visit our website at http://www.overbyte.be

Reply via email to