Skip to main content

Existing Libraries

·2 mins

… continued from the previous post.

Perhaps the most popular exisiting library is golang.org/x/sync/errgroup by Bryan C. Mills:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
	"context"

	"fillmore-labs.com/blog/structured/pkg/task"
	"golang.org/x/sync/errgroup"
)

func doWork(ctx context.Context) error {
	g, ctx := errgroup.WithContext(ctx)

	g.Go(func() error {
		return task.Task(ctx, "task1", processingTime/3, nil)
	})

	g.Go(func() error {
		return task.Task(ctx, "task2", processingTime/2, errFail)
	})

	g.Go(func() error {
		return task.Task(ctx, "task3", processingTime, nil)
	})

	return g.Wait()
}

and the older gopkg.in/tomb.v2 by Gustavo Niemeyer:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
	"context"

	"fillmore-labs.com/blog/structured/pkg/task"
	"gopkg.in/tomb.v2"
)

func doWork(ctx context.Context) error {
	g, ctx := tomb.WithContext(ctx)

	g.Go(func() error {
		return task.Task(ctx, "task1", processingTime/3, nil)
	})

	g.Go(func() error {
		return task.Task(ctx, "task2", processingTime/2, errFail)
	})

	g.Go(func() error {
		return task.Task(ctx, "task3", processingTime, nil)
	})

	return g.Wait()
}

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.