Python与Pascal对话时如何避免竞争条件



所以,最初我要做的事情是这样的:

Pascal_program : write file A
Pascal_program : call Python_program using ShellExecute
Python_program : open file A
Python_program : do the thing to the data
Python_program : write file B and shut down
Pascal_program : read file B

然而,Pascal_program会在调用Python_program后立即开始读取文件B,因此在Python_process有机会写入文件B之前。经过一番尝试和错误,我想出了这个方法,上周成功了:

Pascal program : delete file D (for "dummy"), if it exists
Pascal_program : write file A
Pascal_program : call Python_program using ShellExecute
Python_program : open file A
Python_program : do the thing to the data
Python_program : write file B
Python_program : create file D and shut down
Pascal_program : repeat until FileExists(D)
Pascal_program : read file B

它停止工作了。显然,我只是在向Python倾斜,而不是(正如我从代码中所想的那样(每次都给它带来胜利。它现在又输了。

是的,肯定是比赛条件再次困扰着我,而不是我犯了其他错误——我只需在最后一行之前插入一个延迟命令就可以再次解决问题。但在我的程序中,这不是一个插入免费延迟的好地方。

我不明白为什么我的第一个修复程序不起作用,Python是否以某种方式多任务处理这些光盘操作?还是操作系统?(如果相关,则为Windows 10。(或者操作系统不再及时删除文件D?更重要的是,有人能告诉我该怎么做吗?无论如何,我的解决方案让我觉得很笨拙,我不得不在没有太多背景的Python中做一些非常复杂的事情,这表明了这一点。大概有某种标准的方法来解决这些问题。

谢谢你的建议。


OK,已修复。所以,事实证明,以我极其业余的方式,我不知道过程的存在。我需要的是这样调用它,而不是使用ShellExecute。谢谢Serge Ballesta和stackoverflow,这是我第一次真正提出问题。

Pr:= TProcess.Create(nil);
Pr.Executable:= filepath1+'python.exe';
Pr.Parameters.Add(filepath2+python_program_name+'.py');
Pr.Options := Pr.Options + [poWaitOnExit];
Pr.ShowWindow := swoHide;
Pr.Execute;
Pr.Free; 

我需要使用进程而不是ShellExecute:Pascal代码在我编辑的OP中给出,任何使用Windows的代码都是类似的。

最新更新