README
¶
conpats
conpats contains several common concurrency patterns for convenient use.
go get github.com/kiriyms/conpats
Table of Contents
Quick Rundown
conpatsprovides Worker Pool, Pipeline and Tee.
Worker Pool
- Use
pool.Poolwhen you need to run jobs concurrently with a goroutine limit. - Use
pool.ErrorPoolwhen you need to run jobs that return errors concurrently with a giroutine limit. - Use
pool.ContextPoolwhen you need to run jobs that return errors and receive acontext.Contextargument concurrently with a giroutine limit.
Every Pool must be created using pool.New(...). To convert it use:
.New(...).WithErrors()to get apool.ErrorPool..New(...).WithErrors().WithContext(ctx)to get apool.ContextPool, where thectxparamater specifies your parent context that needs to be passed to all your jobs.
Pipeline
- Use
pipe.PipeFromChan(...)when you need to run all input values from a given channel through a function concurrently. - Use
pipe.PipeFromSlice(...)when you need to run all values of a given slice through a function concurrently.
Both Pipe functions return channels, making it easy to chain several pipes together or using the output channel in other ways, for example:
- Use
pipe.Collect(chan)when you want to block and collect results from a channel into a slice until it is closed.
The Pipeline implementation uses the pool.Pool by default, but can be modified:
- Use
pipe.WithPool(pool)option parameter to specify the Worker Pool implementation that the Pipe will use.
Tee
- Use
tee.NewTee(chan)to create several channels (buffered or unbuffered) that each receive a copy of a value from a providedchanchannel.
Goals
Main goals of this package are:
- Make concurrency easier and reduce boilerplate
- Provide a variety of common concurrency patterns in one place
- Avoid any third-party dependencies
Usage
This section provides simple usage examples of Worker Pool, Pipeline and Tee usage compared to manual implementation. More examples can be found in these patterns' respective READMEs: Pool, Pipe, Tee.
Worker Pool
| Manual | Using pool.Pool |
|---|---|
|
|
Pipeline
| Manual | Using pipe.PipeFromChan() |
|---|---|
|
|
Tee
| Manual | Using tee.NewTee() |
|---|---|
|
|
Note: if one of the output channels is blocked and waiting to be read from, it will cause all other output channels to block too.
Cookbook
The concurrency pattern abstractions in conpats can be easily combined with each other.
To see usage examples that are more complex and closer to real-world problems, check out the Cookbook.
Thoughts & Notes
Making a small Go package has been an enlightening and interesting experience. As a result of this endeavor, I've jotted down some final thoughts.
Status
v1 (core API settled).
Common concurrency patterns are implemented. Possible future improvements:
- Add more patters & utility functions (like Fan-in/Fan-out, Pub-Sub, etc.)
- Add more cookbook examples