ctxs

package
v0.2.15 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2020 License: MIT Imports: 1 Imported by: 4

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ToDoneCh

func ToDoneCh(contexts ...context.Context) []<-chan struct{}

ToDoneCh は、指定された context.Context から done チャネルを取り出してスライスで返します.

取得した done チャネルのスライスを chans.WhenAll() に指定すると全コンテキストが完了するまで 待機することが出来ます。

Example:

<-chans.WhenAll(ctxs.ToDoneCh(contexts...)...) // contexts is []context.Context
Example
package main

import (
	"context"
	"fmt"
	"strconv"
	"time"

	"github.com/devlights/gomy/chans"
	"github.com/devlights/gomy/ctxs"
)

func main() {
	const (
		goroutineCount = 3
	)

	var (
		iter = func(n int) []struct{} { return make([]struct{}, n) }
		g    = func(pCtx context.Context, name string, timeout time.Duration) context.Context {
			ctx, cancel := context.WithTimeout(pCtx, timeout)
			go func() {
				defer cancel()
				fmt.Printf("[%s] start\n", name)
				time.Sleep(10 * time.Millisecond)
				fmt.Printf("[%s] done\n", name)
			}()
			return ctx
		}
	)

	var (
		rootCtx             = context.Background()
		mainCtx, mainCancel = context.WithCancel(rootCtx)
	)

	defer mainCancel()

	contexts := make([]context.Context, goroutineCount)
	for i := range iter(goroutineCount) {
		contexts[i] = g(mainCtx, strconv.Itoa(i), 500*time.Millisecond)
	}

	<-chans.WhenAll(ctxs.ToDoneCh(contexts...)...)

	fmt.Println("[main] done")

}
Output:

[0] start
[1] start
[2] start
[2] done
[0] done
[1] done
[main] done

Types

This section is empty.

Jump to

Keyboard shortcuts

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