并行执行shell命令,但限制了工作(Windows,没有Cygwin) [英] Executing shell commands in parallel but limiting jobs (Windows without Cygwin)

查看:89
本文介绍了并行执行shell命令,但限制了工作(Windows,没有Cygwin)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的.假设我有一个名为myprogram.exe的程序,我必须执行1000次.

Here is what I am trying to do. Suppose I have a program called myprogram.exe, which I have to execute 1000 times.

在Windows下,我通常可以做一些简单的事情:

Under Windows, I could usually do something as simple as:

for /L %n in (1,1,1000) do start /myfolder/myprogram.exe

但是,假设我只有5个CPU线程可以运行1000个myprogram.exe实例,所以我只启动5个,那么当其中一个完成时又启动另一个,等等,直到整个1000结束.

However, suppose I only have 5 CPU threads I can devote to running the 1000 instances of myprogram.exe, such that I launch only 5, then when one of these finishes another one is launched, etc until the whole 1000 end.

在Linux上并使用GNU Parallel,我可以简单地做到:

Under Linux and using GNU Parallel, I could simply do:

seq 1000 | parallel -N0 -j5 "nohup myprogram.exe"

如何在Windows命令行中实现类似的功能?请注意,在我的情况下,使用 Cygwin并不是一个选择,因此在Windows下使用xargs和GNU Parallel也不是一个选择.

How could I achieve something like that in Windows command line? Notice that in my case using Cygwin is not an option, so resorting to xargs and GNU Parallel under Windows are not options either.

推荐答案

这是一种使用Powershell进行进程计数的方法.并使用简单的set /a作为计数器.

Here is a way, by using powershell to do the process count. and using a simply set /a as counter.

@echo off
setlocal enabledelayedexpansion
set /a cnt=0
:counter
if !cnt! lss 1000 (
for /F "tokens=*" %%i in ('powershell ^(Get-Process -Name 'myprogram'^).count') do set proc=%%i
             if !proc! lss 5 (
                          start "C:\myfolder\myprogram.exe"
                          set /a cnt+=1
              )
    goto :counter
   )

如果要查看计数,可以在goto :counter之前的行中添加echo !cnt!.

You could add echo !cnt! in the line before goto :counter if you want to see it count.

无需使用delayedexpansion即可完成操作,但我更喜欢在这里使用.

It can be done without using delayedexpansion but I prefer to use it here.

这篇关于并行执行shell命令,但限制了工作(Windows,没有Cygwin)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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