我有一个程序通过 cmd := exec.Command(name, args ...)
执行一些命令
现在程序正在为 10 个(或更多)不同的目录执行此操作,
我的意思是我为给定路径的 10 个不同目录运行 npm install
。
这个想法是等待
执行过程将结束然后压缩整个文件夹(运行命令npm install的地方)
这里的问题是,当 wait
block 正在执行时,程序停止并等待(当然应该这样做......)但我想继续到下一个目录并且不要等待 wait
(每个目录执行)完成
建议如何妥善处理? 我的意思是在执行模块和 此外,当特定命令完成以在指定目录上运行时,无论程序现在何时在进程中,都会自动压缩
此函数针对不同的目录循环调用 10 次
func (n Node) Build(path string) error {
//e.g. Run npm install which build's nodejs project
command := exec.Command("npm", "install")
command.Dir = n.path
//start the execution
if err := command.Start(); err != nil {
log.Printf("Failed to start cmd: %v", err)
}
// Here I waiting to command to finish to zip the folder
if err := command.Wait(); err != nil {
// Zip folder
}
}
主函数如下调用它
func main() {
//Here I have loop which
for _, dir := range dirs {
switch dir.name {
case "Java":
Build(&Java{path})
case "Go":
Build(&Golang{path,cgoOptions},)
case "Node":
Build(&Node{path})
}
}
最佳答案
你只需要启动尽可能多的goroutines因为你有文件夹来并行执行你的程序,然后等待所有 goroutines 完成使用 wait group .
例子:
import "sync"
func (n Node) Build(wg sync.WaitGroup, path string) error {
wg.Add(1)
defer wg.Done()
//e.g. Run npm install which build's nodejs project
command := exec.Command("npm", "install")
command.Dir = n.path
//start the execution
if err := command.Start(); err != nil {
log.Printf("Failed to start cmd: %v", err)
}
// Here I waiting to command to finish to zip the folder
if err := command.Wait(); err != nil {
// Zip folder
}
}
func main() {
var wg sync.WaitGroup
node := ...
for _, path := range dirs {
go node.Build(wg, path)
}
wg.Wait()
}
UPD:一些解释。我们需要在主进程和所有 goroutine 之间共享一个 WaitGroup 对象。可以将我们的 goroutines 视为逻辑执行线程。并将 WaitGroup 作为线程安全的共享计数器变量。在我们的案例中,每个 goroutine 都是一个单一的逻辑作业。这就是为什么我们 Add()
(即增加) WaitGroup 内部计数器在 thread 开始时增加 1
并通过 Done()
减少 1
在退出 Build()
函数之前调用。和 Wait()
WaitGroup 的方法只是阻塞主进程的执行,直到内部计数器再次变为 0。
关于go - 在 Go 中异步执行命令和 ZIP 文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48559619/