Documentation ¶
Overview ¶
Package parallel is an implementation of structured concurrency for go. https://vorpus.org/blog/notes-on-structured-concurrency-or-go-statement-considered-harmful/
It is designed to help reason about parallel code by ensuring that go-routines are started and stopped in a strictly nested pattern: a child goroutine will never outlive its parent.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Do ¶
func Do(f func(p *P))
Do starts a new parallel execution context and runs it to completion.
After f has run, and after any goroutines started by p.Go have finished, Do will mark p as finished and then return. Any further calls to p.Go will panic.
In practice this means that you can only safely call p.Go from within f, or within the goroutines started by p.Go.
If f, or any goroutine started by p.Go panics, then Do will panic.
The panic behaviour can be overwritten by setting p.OnPanic from within the callback passed to .Do() before any calls to .Go().
Example ¶
package main import ( "github.com/ConradIrwin/parallel" ) var doSomethingElse = func() {} var doSomethingSlow = func() {} func main() { parallel.Do(func(p *parallel.P) { p.Go(doSomethingSlow) p.Go(doSomethingElse) }) }
Output:
func Each ¶
func Each[T any](items []T, f func(T))
Each runs the callback for each item in the slice in parallel.
Example ¶
package main import ( "fmt" "time" "github.com/ConradIrwin/parallel" ) func main() { parallel.Each([]int{1, 2, 3}, func(i int) { time.Sleep(time.Duration(i) * time.Millisecond) fmt.Println(i) }) }
Output: 1 2 3
Types ¶
type P ¶
type P struct { // OnPanic is called when a goroutine panics. You should return // false from this if you don't wish the panic to propagate. // This callback must be safe to call from multiple goroutines. OnPanic func(p any) bool // contains filtered or unexported fields }
P represents the parallel execution of a set of goroutines.