sync

package
v0.2.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 1 Imported by: 0

README

sync

import "github.com/gechr/x/sync"

Package sync provides concurrency helpers.

Index

func Parallel

func Parallel(workers, n int, fn func(i int))

Parallel runs fn(0) through fn(n-1) concurrently with at most workers in flight, blocking until all complete. Each call receives a distinct index, so a goroutine writing results[i] needs no lock; fn must otherwise be safe to call concurrently. workers < 1 runs one call at a time.

Example
// Each call receives a distinct index, so writing results[i]
// needs no lock.
results := make([]int, 5)
xsync.Parallel(3, len(results), func(i int) {
    results[i] = i * i
})
fmt.Println(results)

Output:

[0 1 4 9 16]
Example (SingleWorker)

A single worker runs the calls one at a time, in index order.

xsync.Parallel(1, 3, func(i int) {
    fmt.Println("call", i)
})

Output:

call 0
call 1
call 2

Documentation

Overview

Package sync provides concurrency helpers.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parallel

func Parallel(workers, n int, fn func(i int))

Parallel runs `fn(0)` through `fn(n-1)` concurrently with at most `workers` in flight, blocking until all complete. Each call receives a distinct index, so a goroutine writing `results[i]` needs no lock; `fn` must otherwise be safe to call concurrently. `workers` < 1 runs one call at a time.

Example
package main

import (
	"fmt"

	xsync "github.com/gechr/x/sync"
)

func main() {
	// Each call receives a distinct index, so writing results[i]
	// needs no lock.
	results := make([]int, 5)
	xsync.Parallel(3, len(results), func(i int) {
		results[i] = i * i
	})
	fmt.Println(results)
}
Output:
[0 1 4 9 16]
Example (SingleWorker)

A single worker runs the calls one at a time, in index order.

package main

import (
	"fmt"

	xsync "github.com/gechr/x/sync"
)

func main() {
	xsync.Parallel(1, 3, func(i int) {
		fmt.Println("call", i)
	})
}
Output:
call 0
call 1
call 2

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL