Semaphore for CMD instances running in parallel

I have a .bat that will run X times (with different arguments) at the same moment. I would like them to modify one specific file, but it needs to be executed sequentially with a controlled delay. Ideally, I need a mechanism that would allow only one bat to lock the file and process it as long as it is needed, than to free it, allowing the same for another process.

+4
source share
2 answers

Several improvements to jeb's answer.

No need for an additional lock file. The queue.txt file may serve as its own lock.

In addition, access to the inner block itself must be guaranteed using SUCCESS (errorlevel 0), so that repetition will only occur when the redirect failed. (CALL ) (pay attention to the final space) is a completely unintuitive, but extremely effective way to eliminate any error. Not required here, but (CALL) (note the lack of space) is an effective way to fix the 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 
+7
source

This can be done using the file locking described by dbenham in Dostips: a parallel process with a package and SO: How do you use shared log files in Windows? .

Since windows block the file when opening the write descriptor, they try to access the file with each other, this will lead to an error.

The first process can access the file and write it, the second process will not be able to open it and will loop until the completion of the first process.

 :lockedAppend 2>nul ( >queue.lock ( >>queue.txt echo All text I want ) )||goto :lockedAppend 
+4
source

Source: https://habr.com/ru/post/1481470/


All Articles