首页 > 解决方案 > 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_program 有机会写入文件 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 中做一些非常复杂的事情,它显示了。大概有一些标准的方法来解决这些问题。

感谢您的意见。


好的,修好了。所以,事实证明,以我极其业余的方式,我不知道进程的存在。我需要的是这样调用它,而不是使用 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; 

标签: python

解决方案


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


推荐阅读