Skip to content

Commit

Permalink
Fix: detecting goroutine leak (#191)
Browse files Browse the repository at this point in the history
* test for detecting goroutine leak

* fix goroutine leak
  • Loading branch information
ddddddO authored Jul 1, 2023
1 parent 6c66a9b commit fbacf97
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 7 deletions.
15 changes: 11 additions & 4 deletions input_spliter.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,16 @@ func split(ctx context.Context, r io.Reader) (<-chan string, <-chan error) {
for sc.Scan() {
select {
case <-ctx.Done():
errc <- ctx.Err()
return
default:
l := sc.Text()
if isRootBlockBeginning(l) {
if len(block) != 0 {
blockc <- block
select {
case <-ctx.Done():
return
case blockc <- block:
}
}
block = ""
}
Expand All @@ -41,8 +44,12 @@ func split(ctx context.Context, r io.Reader) (<-chan string, <-chan error) {
errc <- err
return
}
blockc <- block // 最後のRootブロック送出
return
select {
case <-ctx.Done():
return
case blockc <- block: // 最後のRootブロック送出
return
}
}()

return blockc, errc
Expand Down
6 changes: 5 additions & 1 deletion pipeline_tree_grower.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,11 @@ func (dg *defaultGrowerPipeline) worker(ctx context.Context, wg *sync.WaitGroup,
errc <- err
return
}
nodes <- root
select {
case <-ctx.Done():
return
case nodes <- root:
}
}
}
}
Expand Down
7 changes: 5 additions & 2 deletions root_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,11 @@ func (rg *rootGeneratorPipeline) worker(ctx context.Context, wg *sync.WaitGroup,
errc <- err
return
}

rootc <- root
select {
case <-ctx.Done():
return
case rootc <- root:
}
}
}
}
13 changes: 13 additions & 0 deletions tree_handler_output_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"os"
"strings"
"testing"
"time"

"github.com/ddddddO/gtree"
tu "github.com/ddddddO/gtree/testutil"
Expand Down Expand Up @@ -1192,3 +1193,15 @@ children:
})
}
}

func TestOutput_detecting_goroutinelerk(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(500*time.Millisecond))
defer cancel()
w := &strings.Builder{}
r := strings.NewReader(tu.TwentyThousandRoots)
if gotErr := gtree.Output(w, r, gtree.WithMassive(ctx)); gotErr != nil {
if gotErr != context.DeadlineExceeded {
t.Errorf("\ngotErr: \n%v\nwantErr: \n%v", gotErr, context.DeadlineExceeded)
}
}
}

0 comments on commit fbacf97

Please sign in to comment.