简体   繁体   中英

Golang queue: goroutine execution only one at a time

My flow is simple, i need to execute a command in server with 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. The func to execute command is goroutine.

My problem is that can only run one command at a time (goroutine).

The question is: How create queue of goroutine and execute it only one at a time.

To synchronize multiple calls so they execute in sequence, use a buffered channel of length 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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