Could not enter critical section.

Why is it impossible to enter a critical section without Sleep (1)?

type
  TMyThread = class(TThread)
  public
    procedure Execute; override;
  end;

var
  T: TMyThread;
  c: TRTLCriticalSection;

implementation

procedure TForm1.FormCreate(Sender: TObject);
begin
  InitializeCriticalSection(c);
  T := TMyThread.Create(false);
end;

procedure TMyThread.Execute;
begin
  repeat
    EnterCriticalSection(c);
    Sleep(100);
    LeaveCriticalSection(c);
    sleep(1);  // can't enter from another thread without it
  until false;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  EnterCriticalSection(c);
  Caption := 'entered';
  LeaveCriticalSection(c);
end; 

It is not possible to post this due to too much code to text text to text text. Oh, by the way, if a section is created by a stream, then it works fine.

+4
source share
1 answer

There is no guarantee that threads will receive a critical FIFO-based partition (MSDN) . If your current thread always re-acquires the critical section several times after release, then the likelihood that any other waiting threads will most likely never wake up in time to find it themselves.

, , . , , .

+8

Source: https://habr.com/ru/post/1690003/


All Articles