Unable to enter critical section

房东的猫 提交于 2019-12-07 10:34:39

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!