Existing Libraries
Categories:
… continued from the previous post.
Two Popular Choices
Perhaps the most popular exisiting library is golang.org/x/sync/errgroup by Bryan C. Mills:
1package main
2
3import (
4 "context"
5
6 "fillmore-labs.com/blog/structured/pkg/task"
7 "golang.org/x/sync/errgroup"
8)
9
10func doWork(ctx context.Context) error {
11 g, ctx := errgroup.WithContext(ctx)
12
13 g.Go(func() error {
14 return task.Task(ctx, "task1", processingTime/3, nil)
15 })
16
17 g.Go(func() error {
18 return task.Task(ctx, "task2", processingTime/2, errFail)
19 })
20
21 g.Go(func() error {
22 return task.Task(ctx, "task3", processingTime, nil)
23 })
24
25 return g.Wait()
26}
and the older gopkg.in/tomb.v2 by Gustavo Niemeyer:
1package main
2
3import (
4 "context"
5
6 "fillmore-labs.com/blog/structured/pkg/task"
7 "gopkg.in/tomb.v2"
8)
9
10func doWork(ctx context.Context) error {
11 g, ctx := tomb.WithContext(ctx)
12
13 g.Go(func() error {
14 return task.Task(ctx, "task1", processingTime/3, nil)
15 })
16
17 g.Go(func() error {
18 return task.Task(ctx, "task2", processingTime/2, errFail)
19 })
20
21 g.Go(func() error {
22 return task.Task(ctx, "task3", processingTime, nil)
23 })
24
25 return g.Wait()
26}
Summary
In practical scenarios, where numerous goroutines are initiated, structured concurrency guarantees their proper management without leaking resources. The managing goroutine must not exit until all its child goroutines complete. Additionally, structured concurrency guarantees thorough error reporting, preventing any errors from being overlooked or disregarded.
… continued in the next post.