chans

package
v0.15.3 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2024 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package chans contains functions for manipulating channels.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Merge

func Merge[T any](out chan<- T, in ...<-chan T)

Merge sends all values from all in channels to out.

Merge blocks until all ins have closed and all values have been sent. It does not close out.

Example
package main

import (
	"fmt"

	"github.com/bradenaw/juniper/chans"
)

func main() {
	a := make(chan int)
	go func() {
		a <- 0
		a <- 1
		a <- 2
		close(a)
	}()
	b := make(chan int)
	go func() {
		b <- 5
		b <- 6
		b <- 7
		b <- 8
		close(b)
	}()

	out := make(chan int)
	done := make(chan struct{})
	go func() {
		for i := range out {
			fmt.Println(i)
		}
		close(done)
	}()

	chans.Merge(out, a, b)
	close(out)
	<-done

}
Output:

0
1
2
5
6
7
8

func RecvContext

func RecvContext[T any](ctx context.Context, c <-chan T) (T, bool, error)

RecvContext attempts to receive from channel c. If c is closed before or during, returns (_, false, nil). If ctx expires before or during, returns (_, _, ctx.Err()).

func Replicate

func Replicate[T any](src <-chan T, dsts ...chan<- T)

Replicate sends all values sent to src to every channel in dsts.

Replicate blocks until src is closed and all values have been sent to all dsts. It does not close dsts.

Example
package main

import (
	"fmt"
	"sync"

	"github.com/bradenaw/juniper/chans"
)

func main() {
	in := make(chan int)
	go func() {
		in <- 0
		in <- 1
		in <- 2
		in <- 3
		close(in)
	}()

	var wg sync.WaitGroup
	wg.Add(2)
	a := make(chan int)
	go func() {
		for i := range a {
			fmt.Println(i * 2)
		}
		wg.Done()
	}()

	b := make(chan int)
	go func() {
		x := 0
		for i := range b {
			x += i
			fmt.Println(x)
		}
		wg.Done()
	}()

	chans.Replicate(in, a, b)
	close(a)
	close(b)
	wg.Wait()

}
Output:

0
2
4
6
0
1
3
6

func SendContext

func SendContext[T any](ctx context.Context, c chan<- T, item T) error

SendContext sends item on channel c and returns nil, unless ctx expires in which case it returns ctx.Err().

Types

This section is empty.

Jump to

Keyboard shortcuts

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