无法进入关键部分 [英] Unable to enter critical section

查看:139
本文介绍了无法进入关键部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在没有Sleep(1)的情况下无法进入关键部分?

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.

这篇关于无法进入关键部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆