Back to Lo

Parallel Foreach

docs/data/parallel-foreach.md

1.53.0551 B
Original Source

Iterates over elements of a collection and invokes the callback for each element in parallel.

go
import (
    "fmt"
    lop "github.com/samber/lo/parallel"
)

lop.ForEach([]string{"hello", "world"}, func(x string, _ int) {
    fmt.Println(x)
})
// prints lines in any order depending on scheduling

Useful for fire-and-forget work like publishing events or independent side effects:

go
type Job struct{ ID int }

jobs := []Job{{1}, {2}, {3}}
lop.ForEach(jobs, func(j Job, _ int) {
    // process each job concurrently
    // send(j)
})