并行工作的 CMD 实例的信号量 [英] Semaphore for CMD instances working in Parallel

查看:18
本文介绍了并行工作的 CMD 实例的信号量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 .bat 将在同一时刻启动 X 次(使用不同的参数).我希望他们修改一个特定的文件,但必须在可控延迟的情况下按顺序完成.理想情况下,我需要一种机制,只允许一个 bat 锁定文件并在需要时处理它,而不是释放它允许另一个进程执行相同的操作.

I have .bat that would be started X times (with different arguments) at the same moment. I would like them to modify one specific file but it has to be done in sequence with controllable delay. Ideally I would need mechanism that would allow only one bat to lock the file and process it as long as it's needed than release it allowing same thing for another process.

推荐答案

对 jeb 的回答进行了一些改进.

A few improvements to jeb's answer.

不需要额外的锁文件.queue.txt 文件可以作为它自己的锁.

There is no need for an extra lock file. The queue.txt file can serve as its own lock.

此外,必须保证最里面的块以 SUCCESS(错误级别 0)退出,以便仅在重定向失败时重试.(CALL )(注意尾随空格)是一种完全不直观但非常有效的清除任何错误的方法.此处不需要,但 (CALL)(注意缺少空间)是设置错误的有效方法.

Also, the innermost block must be guaranteed to exit with SUCCESS (errorlevel 0) so that the retry only occurs when the redirection failed. (CALL ) (note the trailing space) is a totally non-intuitive, yet extremely efficient way to clear any error. Not needed here, but (CALL) (note the lack of space) is an efficient way to set an error.

:lockedAppend
2>nul (
  >>queue.txt (
    REM Do any amount of processing within this block.
    REM All stdout will safely be appended to the queue
    REM You could even call out to a subroutine, or another batch file

    echo Any text you want

    REM The CALL below ensures that the block exits with ERRORLEVEL 0 - success
    (call )
  )
)||goto :lockedAppend

这篇关于并行工作的 CMD 实例的信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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