为什么没有 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;
由于代码太多,无法发布此内容,因此文本文本文本文本文本。
哦,顺便说一句,如果该部分是由线程创建的,那么它工作正常。
最佳答案
有no guarantee that threads acquire a critical section on a FIFO basis (MSDN) .如果您当前的线程总是在释放临界区后重新获取几个 uop,那么任何其他等待线程可能永远不会及时唤醒以发现它自己可用。
如果您想更好地控制锁序列,您可以使用其他同步对象。事件或队列可能是合适的,但我们真的不知道你想要实现什么。
关于multithreading - 无法进入临界区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47550377/