这是一个用 AHK v1 编写的多进程任务管理示例:从文本文件中读取任务列表,用 Run 以命令行传参方式把每个任务派发给外部 exe 进程,并通过一个进程句柄池(数组 p)记录每个任务的 PID。
核心机制:check_idle() 用 Process, Exist 逐个检查各 PID 是否仍在运行,把已结束的进程从数组中移除;只有当活动进程数低于上限 max 时才继续启动下一个任务,从而控制并发数量。GUI 面板用于输入源文件与最大进程数,Loop, Parse 按行解析任务队列,A_index 记录本次派发序号。
迁移到 AHK v2 的差异:v1 的 Gui, Submit、Process, Exist(通过 ErrorLevel 判断)、p.RemoveAt()、p.maxindex() 在 v2 中应改为面向对象写法(Gui() 对象、ProcessExist() 函数直接返回 PID、ObjRemove() 与数组方法);旧式 % source_file 变量引用在 v2 中需改用表达式。
本文来自于Thinkai’s Blog,thinkai也是我在ahk上面的引路人,对thinkai感兴趣的朋友请关注他的博客。
thinkai的博客简洁、有趣,即便是转载过来我也尽量保持作者原有的风格,主要是方便大家查阅。
exe_file := "test.exe"
Gui, Add, text, x0 y0 w60 h20, 源文件
Gui, Add, Edit, x60 y0 w200 h20 vsource_file
Gui, Add, text, x0 y20 w60 h20, 进程数
Gui, Add, Edit, x60 y20 w200 h20 vmax, 10
Gui, Add, Button, x0 y40 w160 h20 gstart vstart, 开始
gui, Add, text, x0 y60 w160 h100 vshow
Gui, Show, x0 y0, 多进程示例
return
start:
GuiControl, Disable, start
Gui, Submit, nohide
FileRead, content, % source_file
Loop, Parse, content, `n, `r
{
while(!check_idle())
Sleep, 1000
info := StrSplit(res,",")
GuiControl, , show, % "信息:" info[1] " " info[2] "`n本次运行数量:" A_index "`n当前线程数:" p.maxindex()+1
Run, % exe_file " " info[1] " " info[2], , , pid ;传参方式传递数据
p.Push(pid)
}
return
GuiClose:
ExitApp
check_idle(){
global p,max
for k,v in p
{
Process, Exist, % v
if !ErrorLevel
p.RemoveAt(k)
}
return (p.maxindex()<max)
}

