Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

windows - Semaphore for CMD instances working in Parallel

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A few improvements to jeb's answer.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...