-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* utility for managing group of goroutines * refactor context to StopChan * remove limits * leftovers * leftovers round #2 * lint
- Loading branch information
Showing
2 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package utils | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
) | ||
|
||
var _ ThreadControl = &threadControl{} | ||
|
||
// ThreadControl is a helper for managing a group of goroutines. | ||
type ThreadControl interface { | ||
// Go starts a goroutine and tracks the lifetime of the goroutine. | ||
Go(fn func(context.Context)) | ||
// Close cancels the goroutines and waits for all of them to exit. | ||
Close() | ||
} | ||
|
||
func NewThreadControl() *threadControl { | ||
tc := &threadControl{ | ||
stop: make(chan struct{}), | ||
} | ||
|
||
return tc | ||
} | ||
|
||
type threadControl struct { | ||
threadsWG sync.WaitGroup | ||
stop StopChan | ||
} | ||
|
||
func (tc *threadControl) Go(fn func(context.Context)) { | ||
tc.threadsWG.Add(1) | ||
go func() { | ||
defer tc.threadsWG.Done() | ||
ctx, cancel := tc.stop.NewCtx() | ||
defer cancel() | ||
fn(ctx) | ||
}() | ||
} | ||
|
||
func (tc *threadControl) Close() { | ||
close(tc.stop) | ||
tc.threadsWG.Wait() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package utils | ||
|
||
import ( | ||
"context" | ||
"sync/atomic" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestThreadControl_Close(t *testing.T) { | ||
n := 10 | ||
tc := NewThreadControl() | ||
|
||
finished := atomic.Int32{} | ||
|
||
for i := 0; i < n; i++ { | ||
tc.Go(func(ctx context.Context) { | ||
<-ctx.Done() | ||
finished.Add(1) | ||
}) | ||
} | ||
|
||
tc.Close() | ||
|
||
require.Equal(t, int32(n), finished.Load()) | ||
} |