0

我有两个脚本在同一台机器上作为无限循环在 python 中运行,它们不断监视一些值。他们通过 file.txt 进行通信

B 将消息添加到 file.txt 以便它们堆积起来。当 A 检查 file.txt 时,它会将它们读入并清空 file.txt

一个

while true:
    Open file.txt if B is not using it or when B is done
    f = open('file.txt', 'r+') 
    message=f.read()    #read all the messages that have accumulated
    f.truncate()        #delete the messages 
    f.close()

    ---use message do other things

while true:
    ---Gather information for the message

    Open file.txt if A is not using it or when A is done
    f = open('file.txt’,’a’)  
    f.write(‘message’)
    f.close()

泡菜是我希望每个脚本仅在另一个脚本不使用它时打开 file.txt,或者等待它停止使用。因此,当 B 正在写入并且 A 想要读取时,B 将暂停一小段时间然后继续。

无需同步两者。实际上,我希望它们是独立的,而不是线程化的或并行运行的。例如,B 可以循环,而 A 只能循环一次,反之亦然。或者,如果 A 由于某种原因被延迟,则消息只会堆积在 file.txt 中,因为 B 继续运行。

我已阅读有关锁定文件的信息。是否可以在每个脚本中执行以下操作:

A
if "file locked by B":
    wait for unlock

lock file 
open file
read from file
empty file 
close file
unlock file

“等待解锁”和“文件被 B 锁定”和“锁定文件”会使用什么工具?

4

0 回答 0