Skip to content

Instantly share code, notes, and snippets.

@reusee
Created February 22, 2020 01:29
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 reusee/00f586bba01b9584b82173f8bf1d4950 to your computer and use it in GitHub Desktop.
Save reusee/00f586bba01b9584b82173f8bf1d4950 to your computer and use it in GitHub Desktop.
foo
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"sync"
)
func main() {
// 输入,可以是任意 io.Reader
input := bytes.NewReader([]byte("foobarbaz"))
// 最大 4 个处理线程
sem := make(chan struct{}, 4)
cond := sync.NewCond(new(sync.Mutex))
next := 0
ready := 0
for {
// 分段读取
r := &io.LimitedReader{
R: input,
N: 2,
}
chunk, err := ioutil.ReadAll(r)
if len(chunk) > 0 {
sem <- struct{}{}
i := next
next++
go func() {
defer func() {
<-sem
}()
// 按顺序输出
cond.L.Lock()
for i != ready {
cond.Wait()
}
fmt.Printf("%s\n", chunk)
ready++
cond.Broadcast()
cond.L.Unlock()
}()
}
if err == io.EOF {
break
} else if err != nil {
panic(err)
}
if len(chunk) == 0 {
break
}
}
for i := 0; i < cap(sem); i++ {
sem <- struct{}{}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment