简体   繁体   English

"Golang队列:一次只执行一个goroutine"

[英]Golang queue: goroutine execution only one at a time

My flow is simple, i need to execute a command in server with Golang:我的流程很简单,我需要使用 Golang 在服务器中执行命令:

func ExecuteERPChange(params string) error{
    app := "xxxx"

    arg0 := "xxxx"
    arg1 := "-p xxxx"
    arg2 := "-h xxxx"
    arg3 := "--param"

    cmd := exec.Command(app, arg0, arg1, arg2, arg3, params)
    _, err := cmd.Output()

    if err != nil {
        fmt.Println(err.Error())
        return err
    }

    return nil
}

I created a http server in golang for received params to call command.我在 golang 中为接收到的参数创建了一个 http 服务器来调用命令。 The func to execute command is goroutine.执行命令的函数是 goroutine。

My problem is that can only run one command at a time (goroutine).我的问题是一次只能运行一个命令(goroutine)。

The question is: How create queue of goroutine and execute it only one at a time.问题是:如何创建 goroutine 队列并一次只执行一个。

To synchronize multiple calls so they execute in sequence, use a buffered channel of length 1.要同步多个调用以便它们按顺序执行,请使用长度为 1 的缓冲通道。

Trying to push in it will allow up to channel length routines to execute in parallel.尝试推入它将允许最多通道长度的例程并行执行。

package main

import (
    "fmt"
    "os"
    "time"
)

func main() {
    limiter := make(chan struct{}, 1)
    for i := 0; i < 10; i++ {
        i := i
        go func() {
            // ...say this is the http handler...
            
            // Try to fill the channel, 
            // it allows up to one non-blocking writes.
            limiter <- struct{}{}

            // ... Do some job
            fmt.Fprintf(os.Stderr, "routine #%v is running\n", i)
            <-time.After(time.Millisecond * 250)

            // Then release the value in the channel 
            // so among other routines trying to push,
            // one will succeed and continue.
            <-limiter
        }()
    }
    <-time.After(time.Second * 3)
}

To increase the concurrency, increase the limiter channel length.要增加并发性,请增加限制器通道长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM