Skip to content

Instantly share code, notes, and snippets.

@guerbai
Created February 16, 2020 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guerbai/b97d7086cf7d21e1fc80e09acbab182f to your computer and use it in GitHub Desktop.
Save guerbai/b97d7086cf7d21e1fc80e09acbab182f to your computer and use it in GitHub Desktop.
[并发洗数go]
var MAX_PARALLEL = 50
var sem = make(chan int, MAX_PARALLEL)
var f = "./ids.csv"
func bizFunc(id int64) {
defer func(){<-sem}()
// biz code.
}
func parallelWork() {
file, err := os.Open(f)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
count := 0
startTime := time.Now().Unix()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if line == `"id"` || line == "" {
continue
}
sem <- 1
id, err := strconv.Atoi(line[1:len([]byte(line))-1]) // 去除双引号
if err != nil {
fmt.Println(err)
}
count++
if count % 10000 == 0 {
fmt.Printf("%v ids processed\n", count)
}
go bizFunc(ctx, int64(id))
}
endTime := time.Now().Unix()
fmt.Printf("cost time: %v", endTime - startTime)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment