【问题标题】:bounded parallelism to hash strings [duplicate]哈希字符串的有限并行性[重复]
【发布时间】:2018-05-14 01:47:22
【问题描述】:

尝试解决从文件中读取电话号码的问题(逐行)并在 go 中并发散列(md5),最大并发进程数为 100,创建固定数量的 goroutine。尝试使用 go pipeline 和有界并行,但没有奏效。请问有什么指导吗?

这是我试过的,https://play.golang.org/p/vp7s512l8w4

【问题讨论】:

标签: go hash concurrency


【解决方案1】:
package main

import (
    "bufio"
    "fmt"
    "os"
    "sync"
)

func hashPhoneNumers(phoneNO string, ch chan struct{}, group *sync.WaitGroup) {
    do_hash(phoneNO)
    <-ch
    group.Done()
}

func do_hash(s string) {
    fmt.Println("do hash: ", s)
}

func main() {
    c := make(chan struct{}, 100)
    file, err := os.Open("file.txt")
    if err != nil {
        fmt.Println(err)
        os.Exit(-1)
    }
    defer file.Close()
    line := bufio.NewScanner(file)

    wg := sync.WaitGroup{}
    for line.Scan() {
        // with a maximum of 100 concurrent process maximum
        c <- struct{}{}
        wg.Add(1)
        go hashPhoneNumers(line.Text(), c, &wg)
    }

    // wait all goroutines done
    wg.Wait()
    close(c)
}

这很好用

【讨论】:

  • 非常感谢。问题,如果do_hash是一个繁重的操作,有100个worker,是不是要等到至少释放一个?
  • 等到所有 100 个 worker goroutine 完成他们的工作并退出
  • 很好,那么在这种情况下 c
  • 像一个计数器,c
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
  • 2021-04-25
  • 2013-08-04
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
相关资源
最近更新 更多