Skip to content

wait out chan finish job #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions 17-ring-buffer-channel/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,19 @@ import "log"
// Ref:
// https://tanzu.vmware.com/content/blog/a-channel-based-ring-buffer-in-go

func NewRingBuffer(inCh, outCh chan int) *ringBuffer {
func NewRingBuffer(inCh, outCh chan int, down chan bool) *ringBuffer {
return &ringBuffer{
inCh: inCh,
outCh: outCh,
down: down,
}
}

// ringBuffer throttle buffer for implement async channel.
type ringBuffer struct {
inCh chan int
outCh chan int
down chan bool
}

func (r *ringBuffer) Run() {
Expand All @@ -28,13 +30,15 @@ func (r *ringBuffer) Run() {
r.outCh <- v
}
}
r.down <- true
close(r.outCh)
}

func main() {
inCh := make(chan int)
outCh := make(chan int, 4) // try to change outCh buffer to understand the result
rb := NewRingBuffer(inCh, outCh)
down := make(chan bool, 1)
rb := NewRingBuffer(inCh, outCh, down)
go rb.Run()

for i := 0; i < 10; i++ {
Expand All @@ -43,8 +47,9 @@ func main() {

close(inCh)

for res := range outCh {
log.Println(res)
if <-down == true {
for res := range outCh {
log.Println(res)
}
}

}