go - 在 Go 中异步执行命令和 ZIP 文件夹

标签 go

我有一个程序通过 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})
    }
}

类似于这篇文章 Using inheritance of builders in GO

最佳答案

你只需要启动尽可能多的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/

相关文章:

go - 去http.FileServer流错误的文件

go - 导入语句位置

go - 如何运行构建Go文件后生成的Go可执行文件?

go - 在本地使用带有 go mod 的子包

go - Golang Goroutine 背后的架构是什么?

macos - 当构建参数包含`-gcflags“all = -N -l”并在MacOS中导入net/http时,构建失败

redirect - 重定向的上下文超时而不是使用客户端超时?

random - 如何正确播种随机数生成器

types - 确定 var 是否为自定义类型

go - 你如何优雅地退出 go uber fx 应用程序