Why is it imposible to enter 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;
Can't post this because of too much code so text text text text text. Oh by the way if the section is created by the thread then it is working fine.
There is no guarantee that threads acquire a critical section on a FIFO basis (MSDN). If your current thread always re-acquires the critical section a few uops after releasing it then chances are that any other waiting threads will likely never wake in time to find it available themselves.
If you want better control of lock sequencing there are other synchronization objects you can use. Events or a queue might be suitable but we don't really know what you are trying to achieve.
来源:https://stackoverflow.com/questions/47550377/unable-to-enter-critical-section