1

我有一个resourceId需要并行循环的数组。并URL为每个资源生成,然后放入一个映射中,该映射是键(resourcecId),值是 url。

我得到了下面的代码来完成这项工作,但我不确定这是否是正确的方法。我在这里使用sizedwaitgroup来并行化resourceId列表。并且在将数据写入地图时也使用锁定地图。我确信这不是有效的代码,因为使用 lock 然后使用 sizedwaitgroup 会有一些性能问题。

最好和最有效的方法是什么?我应该在这里使用频道吗?我想控制我应该拥有多少而不是运行resourceId列表长度的并行度。如果任何resourceIdurl 生成失败,我想将其记录为错误,resourceId但不要中断并行运行的其他 goroutine 以获取为 other 生成的 url resourceId

例如:如果有 10 个资源,其中 2 个失败,则记录这 2 个的错误,并且 map 应该有剩余 8 个的条目。

// running 20 threads in parallel
swg := sizedwaitgroup.New(20)
var mutex = &sync.Mutex{}
start := time.Now()
m := make(map[string]*customerPbV1.CustomerResponse)
for _, resources := range resourcesList {
  swg.Add()
  go func(resources string) {
    defer swg.Done()
    customerUrl, err := us.GenerateUrl(clientId, resources, appConfig)
    if err != nil {
      errs.NewWithCausef(err, "Could not generate the url for %s", resources)
    }
    mutex.Lock()
    m[resources] = customerUrl
    mutex.Unlock()
  }(resources)
}
swg.Wait()

elapsed := time.Since(start)
fmt.Println(elapsed)

注意:上面的代码将从多个读取器线程中以高吞吐量调用,因此它需要执行良好。

4

3 回答 3

5

我不确定sizedwaitgroup它是什么,也没有解释,但总的来说,这种方法在 Go 中看起来并不是很典型。就此而言,“最佳”是一个见仁见智的问题,但 Go 中最典型的方法是这样的:

func main() {
    wg := new(sync.WaitGroup)
    start := time.Now()
    numWorkers := 20
    m := make(map[string]*customerPbV1.CustomerResponse)
    work := make(chan string)
    results := make(chan result)
    for i := 0; i < numWorkers; i++ {
        wg.Add(1)
        go worker(work, results)
    }
    go func() {
        for _, resources := range resourcesList {
            work <- resources
        }
        close(work)
    }()

    go func() {
        wg.Wait()
        close(results)
    }()

    for result := range results {
        m[result.resources] = result.response
    }

    elapsed := time.Since(start)
    fmt.Println(elapsed)
}

type result struct {
    resources string
    response  *customerPbV1.CustomerResponse
}

func worker(ch chan string, r chan result) {
    for w := range ch {
        customerUrl, err := us.GenerateUrl(clientId, w, appConfig)
        if err != nil {
            errs.NewWithCausef(err, "Could not generate the url for %s", resources)
            continue
        }
        r <- result{w, customerUrl}
    }
}

(虽然,根据名称,我假设errs.NewWithCause实际上并没有处理错误,而是返回一个,在这种情况下,当前代码会将它们放在地板上,并且适当的解决方案将有一个额外chan error的处理错误:

func main() {
    wg := new(sync.WaitGroup)
    start := time.Now()
    numWorkers := 20
    m := make(map[string]*customerPbV1.CustomerResponse)
    work := make(chan string)
    results := make(chan result)
    errors := make(chan error)
    for i := 0; i < numWorkers; i++ {
        wg.Add(1)
        go worker(work, results, errors)
    }

    go func() {
        for _, resources := range resourcesList {
            work <- resources
        }
        close(work)
    }()

    go func() {
        wg.Wait()
        close(results)
        close(errors)
    }()

    go func() {
        for err := range errors {
            // Do something with err
        }
    }()

    for result := range results {
        m[result.resources] = result.response
    }

    elapsed := time.Since(start)
    fmt.Println(elapsed)
}

type result struct {
    resources string
    response  *customerPbV1.CustomerResponse
}

func worker(ch chan string, r chan result, errs chan error) {
    for w := range ch {
        customerUrl, err := us.GenerateUrl(clientId, w, appConfig)
        if err != nil {
            errs <- errs.NewWithCausef(err, "Could not generate the url for %s", resources)
            continue
        }
        r <- result{w, customerUrl}
    }
}
于 2022-02-24T22:21:30.613 回答
1

我已经创建了带有注释的示例代码。请阅读评论。

注意:查询功能将在 1 秒后休眠。

package main

import (
    "errors"
    "fmt"
    "log"
    "math/rand"
    "runtime"
    "strconv"
    "sync"
    "time"
)

type Result struct {
    resource string
    val      int
    err      error
}

/*
CHANGE Result struct to this
result struct will collect all you need to create map
type Result struct {
    resources string
    customerUrl *customerPbV1.CustomerResponse
    err error
}
*/

// const numWorker = 8

func main() {
    now := time.Now()
    rand.Seed(time.Now().UnixNano())
    m := make(map[string]int)
    // m := make(map[string]*customerPbV1.CustomerResponse)                 // CHANGE TO THIS

    numWorker := runtime.NumCPU()
    fmt.Println(numWorker)
    chanResult := make(chan Result)

    go func() {
        for i := 0; i < 20; i++ {
            /*
             customerUrl, err := us.GenerateUrl(clientId, resources, appConfig)
             we asume i is resources
             chanResult <- Result {resource: strconv.Itoa(i)}
            */
            chanResult <- Result{ // this will block until chanResult is consume in line 68
                resource: strconv.Itoa(i),
            }
        }
        close(chanResult)
    }()

    var wg sync.WaitGroup
    cr := make(chan Result)
    wg.Add(numWorker)

    go func() {
        wg.Wait()
        close(cr) // NOTE: don't forget to close cr
    }()

    go func() {
        for i := 0; i < numWorker; i++ { // this for loop will run goroutine
            go func(x int) {
                for job := range chanResult { // unblock chan on line 49
                    log.Println("worker", x, "working on", job.resource)
                    x, err := query(job.resource) // TODO: customerUrl, err := us.GenerateUrl(clientId, resources, appConfig)
                    cr <- Result{                 // send to channel, will block until it consume. Consume is in MAIN goroutine "line 84"
                        resource: job.resource,
                        val:      x,
                        err:      err,
                    }
                }
                wg.Done()
            }(i)
        }
    }()

    counterTotal := 0
    counterSuccess := 0
    for res := range cr { // will unblock channel in line 71
        if res.err != nil {
            log.Printf("error found %s. stack trace: %s", res.resource, res.err)
        } else {
            m[res.resource] = res.val // NOTE: save to map
            counterSuccess++
        }
        counterTotal++
    }
    log.Printf("%d/%d of total job run", counterSuccess, counterTotal)
    fmt.Println("final :", m)
    fmt.Println("len m", len(m))

    fmt.Println(runtime.NumGoroutine())
    fmt.Println(time.Since(now))
}

func query(s string) (int, error) {
    time.Sleep(time.Second)
    i, err := strconv.Atoi(s)
    if err != nil {
        return 0, err
    }

    if i%3 == 0 {
        return 0, errors.New("i divided by 3")
    }
    ms := i + 500 + rand.Intn(500)
    return ms, nil
}

游乐场:https ://go.dev/play/p/LeyE9n1hh81

于 2022-02-28T01:05:37.600 回答
0

这是一个纯渠道解决方案(游乐场)。我认为性能真的取决于GenerateUrl我的代码中的 or generateURL。我还要指出的另一件事是,正确的术语是并发而不是并行

package main

import (
    "errors"
    "log"
    "strconv"
    "strings"
)

type result struct {
    resourceID, url string
    err             error
}

func generateURL(resourceID string) (string, error) {
    if strings.HasPrefix(resourceID, "error-") {
        return "", errors.New(resourceID)
    }
    return resourceID, nil
}

func main() {
    // This is the resource IDs
    resources := make([]string, 10000)
    for i := 0; i < 10000; i++ {
        s := strconv.Itoa(i)
        if i%10 == 0 {
            resources[i] = "error-" + s
        } else {
            resources[i] = "id-" + s
        }
    }

    numOfChannel := 20
    // We send result through this channel to the resourceMap
    ch := make(chan result, 10)
    // These are the channels that go routine receives resource ID from
    channels := make([]chan string, numOfChannel)
    // After processing all resources, this channel is used to signal the go routines to exit
    done := make(chan struct{})

    for i := range channels {
        c := make(chan string)
        channels[i] = c

        go func() {
            for {
                select {
                case rid := <-c:
                    u, err := generateURL(rid)
                    ch <- result{rid, u, err}
                case _, ok := <-done:
                    if !ok {
                        break
                    }
                }
            }
        }()
    }

    go func() {
        for i, r := range resources {
            channels[i%numOfChannel] <- r
        }
    }()

    resourceMap := make(map[string]string)
    i := 0
    for p := range ch {
        if p.err != nil {
            log.Println(p.resourceID, p.err)
        } else {
            resourceMap[p.resourceID] = p.url
        }
        i++
        if i == len(resources)-1 {
            break
        }
    }

    close(done)
}
于 2022-03-04T16:13:31.840 回答