Description
Package goroutines is an efficient, flexible, and lightweight goroutine pool written in Go. It provides a easy way to deal with several kinds of concurrent tasks with limited resource.
Inspired by fastsocket, the implementation is based on channel. It adopts pubsub model for dispatching tasks, and holding surplus tasks in queue if submitted more than the capacity of pool.
goroutines alternatives and similar packages
Based on the "Go Tools" category.
Alternatively, view goroutines alternatives based on common mentions on social networks and blogs.
-
JuiceFS
JuiceFS is a distributed POSIX file system built on top of Redis and S3. -
JSON-to-Go
Translates JSON into a Go type in your browser instantly (original) -
gb
An easy to use project based build tool for the Go programming language. -
kube-prompt
An interactive kubernetes client featuring auto-complete. -
go-critic
The most opinionated Go source code linter for code audit. -
The Go Play Space
Advanced Go Playground frontend written in Go, with syntax highlighting, turtle graphics mode, and more -
Peanut
🐺 Deploy Databases and Services Easily for Development and Testing Pipelines. -
golang-tutorials
Golang Tutorials. Learn Golang from Scratch with simple examples. -
xdg-go
Go implementation of the XDG Base Directory Specification and XDG user directories -
rts
RTS: request to struct. Generates Go structs from JSON server responses. -
typex
[TOOL, CLI] - Filter and examine Go type structures, interfaces and their transitive dependencies and relationships. Export structural types as TypeScript value object or bare type representations. -
gothanks
GoThanks automatically stars Go's official repository and your go.mod github dependencies, providing a simple way to say thanks to the maintainers of the modules you use and the contributors of Go itself. -
zb
an opinionated repo based tool for linting, testing and building go source -
Viney's go-cache
A flexible multi-layer Go caching library to deal with in-memory and shared cache by adopting Cache-Aside pattern. -
go-lock
go-lock is a lock library implementing read-write mutex and read-write trylock without starvation -
An exit strategy for go routines.
An exit strategy for go routines -
generator-go-lang
A Yeoman generator to get new Go projects started. -
version
Go package to present your CLI version with an upgrade notice. -
go-james
James is your butler and helps you to create, build, debug, test and run your Go projects -
import "github/shuLhan/share"
A collection of libraries and tools written in Go; including DNS, email, git ini file format, HTTP, memfs (embedding file into Go), paseto, SMTP, TOTP, WebSocket, XMLRPC, and many more. -
PDF to Image Converter Using Golang
This project will help you to convert PDF file to IMAGE using golang. -
go-sanitize
:bathtub: Golang library of simple to use sanitation functions -
go-whatsonchain
:link: Unofficial golang implementation for the WhatsOnChain API -
gomodrun
The forgotten go tool that executes and caches binaries included in go.mod files. -
docs
Automatically generate RESTful API documentation for GO projects - aligned with Open API Specification standard -
Proofable
General purpose proving framework for certifying digital assets to public blockchains -
channelize
A websocket framework to manage outbound streams. Allowing to have multiple channels per connection that includes public and private channels. -
ciiigo
[mirror] Go static website generator with asciidoc markup language -
MessageBus implementation for CQRS projects
CQRS Implementation for Golang language -
redispubsub
Redis Streams queue driver for https://godoc.org/gocloud.dev/pubsub package -
go-slices
Helper functions for the manipulation of slices of all types in Go -
modver
Compare two versions of a Go module to check the version-number change required (major, minor, or patchlevel), according to semver rules. -
go-pipl
:family_man_woman_boy: Unofficial golang implementation for the pipl.com search API -
go-mattercloud
:cloud: Unofficial Go implementation for the MatterCloud API
Access the most powerful time series database as a service
* Code Quality Rankings and insights are calculated and provided by Lumnify.
They vary from L1 to L5 with "L5" being the highest.
Do you think we are missing an alternative of goroutines or a related project?
README
goroutines
Package goroutines is an efficient, flexible, and lightweight goroutine pool written in Go. It provides a easy way to deal with several kinds of concurrent tasks with limited resource.
Inspired by fastsocket, the implementation is based on channel. It adopts pubsub model for dispatching tasks, and holding surplus tasks in queue if submitted more than the capacity of pool.
Features
- Spawning and managing arbitrary number of asynchronous goroutines as a worker pool.
- Dispatch tasks to workers through pubsub model with specified queue size.
- Adjust the worker numbers based on the usage periodically.
- Easy to use when dealing with concurrent one-time batch jobs.
- Monitor current status by metrics
Table of Contents
Installation
go get github.com/viney-shih/goroutines
Get Started
Basic usage of Pool in blocking mode
By calling Schedule()
, it schedules the task executed by worker (goroutines) in the Pool.
It will be blocked until the workers accepting the request.
taskN := 7
rets := make(chan int, taskN)
// allocate a pool with 5 goroutines to deal with those tasks
p := goroutines.NewPool(5)
// don't forget to release the pool in the end
defer p.Release()
// assign tasks to asynchronous goroutine pool
for i := 0; i < taskN; i++ {
idx := i
p.Schedule(func() {
// sleep and return the index
time.Sleep(20 * time.Millisecond)
rets <- idx
})
}
// wait until all tasks done
for i := 0; i < taskN; i++ {
fmt.Println("index:", <-rets)
}
// Unordered output:
// index: 3
// index: 1
// index: 2
// index: 4
// index: 5
// index: 6
// index: 0
Basic usage of Pool in nonblocking mode
By calling ScheduleWithTimeout()
, it schedules the task executed by worker (goroutines) in the Pool within the specified period.
If it exceeds the time and doesn't be accepted, it will return error ErrScheduleTimeout
.
totalN, taskN := 5, 5
pause := make(chan struct{})
rets := make(chan int, taskN)
// allocate a pool with 5 goroutines to deal with those 5 tasks
p := goroutines.NewPool(totalN)
// don't forget to release the pool in the end
defer p.Release()
// full the workers which are stopped with the `pause`
for i := 0; i < taskN; i++ {
idx := i
p.ScheduleWithTimeout(50*time.Millisecond, func() {
<-pause
rets <- idx
})
}
// no more chance to add any task in Pool, and return `ErrScheduleTimeout`
if err := p.ScheduleWithTimeout(50*time.Millisecond, func() {
<-pause
rets <- taskN
}); err != nil {
fmt.Println(err.Error())
}
close(pause)
for i := 0; i < taskN; i++ {
fmt.Println("index:", <-rets)
}
// Unordered output:
// schedule timeout
// index: 0
// index: 3
// index: 2
// index: 4
// index: 1
Advanced usage of Batch jobs
To deal with batch jobs and consider the performance, we need to run tasks concurrently. However, the use case usually happen once and need not maintain a Pool for reusing it. I wrap this patten and call it Batch
. Here comes an example.
taskN := 11
// allocate a one-time batch job with 3 goroutines to deal with those tasks.
// no need to spawn extra goroutine by specifing the batch size consisting with the number of tasks.
b := goroutines.NewBatch(3, goroutines.WithBatchSize(taskN))
// don't forget to close batch job in the end
defer b.Close()
// pull all tasks to this batch queue
for i := 0; i < taskN; i++ {
idx := i
b.Queue(func() (interface{}, error) {
// sleep and return the index
time.Sleep(10 * time.Millisecond)
return idx, nil
})
}
// tell the batch that's all need to do
// DO NOT FORGET THIS OR GOROUTINES WILL DEADLOCK
b.QueueComplete()
for ret := range b.Results() {
if ret.Error() != nil {
panic("not expected")
}
fmt.Println("index:", ret.Value().(int))
}
// Unordered output:
// index: 3
// index: 1
// index: 2
// index: 4
// index: 5
// index: 6
// index: 10
// index: 7
// index: 9
// index: 8
// index: 0
See the examples, documentation and article for more details.
Options
PoolOption
The PoolOption
interface is passed to NewPool
when creating Pool.
• WithTaskQueueLength( length int
)
It sets up the length of task queue for buffering tasks before sending to goroutines. The default queue length is 0
.
• WithPreAllocWorkers( size int
)
It sets up the number of workers to spawn when initializing Pool. Without specifying this, It initialize all numbers of goroutines consisting with Pool size at the beginning.
• WithWorkerAdjustPeriod( period time.Duration
)
It sets up the duration to adjust the worker size, and needs to be used with WithPreAllocWorkers
at the same time. By specifying both, it enables the mechanism to adjust the number of goroutines according to the usage dynamically.
BatchOption
The BatchOption
interface is passed to NewBatch
when creating Batch.
• WithBatchSize( size int
)
It specifies the batch size used to forward tasks.
By default, it needs to spawn an extra goroutine to prevent deadlocks.
It's helpful by specifing the batch size consisting with the number of tasks without an extra goroutine (see the example). The default batch size is 10
.
References
- https://github.com/faceair/fastsocket
- https://github.com/valyala/fasthttp
- https://github.com/Jeffail/tunny
- https://github.com/go-playground/pool
- https://github.com/panjf2000/ants
License
*Note that all licence references and agreements mentioned in the goroutines README section above
are relevant to that project's source code only.