modulepackage
0.0.0-20180306012644-bacd9c7ef1dd
Repository: https://github.com/modern-go/concurrent.git
Documentation: pkg.go.dev
# README
concurrent
- concurrent.Map: backport sync.Map for go below 1.9
- concurrent.Executor: goroutine with explicit ownership and cancellable
concurrent.Map
because sync.Map is only available in go 1.9, we can use concurrent.Map to make code portable
m := concurrent.NewMap()
m.Store("hello", "world")
elem, found := m.Load("hello")
// elem will be "world"
// found will be true
concurrent.Executor
executor := concurrent.NewUnboundedExecutor()
executor.Go(func(ctx context.Context) {
everyMillisecond := time.NewTicker(time.Millisecond)
for {
select {
case <-ctx.Done():
fmt.Println("goroutine exited")
return
case <-everyMillisecond.C:
// do something
}
}
})
time.Sleep(time.Second)
executor.StopAndWaitForever()
fmt.Println("executor stopped")
attach goroutine to executor instance, so that we can
- cancel it by stop the executor with Stop/StopAndWait/StopAndWaitForever
- handle panic by callback: the default behavior will no longer crash your application
# Functions
NewMap creates a thread safe Map.
NewUnboundedExecutor creates a new UnboundedExecutor, UnboundedExecutor can not be created by &UnboundedExecutor{} HandlePanic can be set with a callback to override global HandlePanic.
# Variables
ErrorLogger is used to print out error, can be set to writer other than stderr.
GlobalUnboundedExecutor has the life cycle of the program itself any goroutine want to be shutdown before main exit can be started from this executor GlobalUnboundedExecutor expects the main function to call stop it does not magically knows the main function exits.
HandlePanic logs goroutine panic by default.
InfoLogger is used to print informational message, default to off.
# Structs
Map is a wrapper for sync.Map introduced in go1.9.
UnboundedExecutor is a executor without limits on counts of alive goroutines it tracks the goroutine started by it, and can cancel them when shutdown.
# Interfaces
Executor replace go keyword to start a new goroutine the goroutine should cancel itself if the context passed in has been cancelled the goroutine started by the executor, is owned by the executor we can cancel all executors owned by the executor just by stop the executor itself however Executor interface does not Stop method, the one starting and owning executor should use the concrete type of executor, instead of this interface.