promise

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2025 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Package promise には、Future/Promiseパターンの例が配置されています。

REFERENCES

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewPromise

func NewPromise[T any]() (*Future[T], *Promise[T])

NewPromise は、FutureとPromiseを生成して返します。

Types

type Future

type Future[T any] struct {
	// contains filtered or unexported fields
}

Future[T] は、「今はまだ得られていないが将来得られるはずの入力」を表します。

func (*Future[T]) Get

func (me *Future[T]) Get() T

Get は、この Future[T] の結果を返します。

func (*Future[T]) IsDone

func (me *Future[T]) IsDone() bool

IsDone は、この Future[T] が完了したかどうかを返します。

type Promise

type Promise[T any] struct {
	// contains filtered or unexported fields
}

Promise[T] は、「将来値を提供するという約束」を表します。

Example
var (
	f1, p1 = NewPromise[int]()
	f2, p2 = NewPromise[string]()
	wg     sync.WaitGroup
)

wg.Add(3)

// f1に依存する処理
//
// f2の状態に関係なく、f1が完了したら完了する
go func(f *Future[int]) {
	defer wg.Done()
	fmt.Printf("f1=%v\n", f1.Get())
}(f1)

// f2に依存する処理
//
// f1の状態に関係なく、f2が完了したら完了する
go func(f *Future[string]) {
	defer wg.Done()
	fmt.Printf("f2=%v\n", f2.Get())
}(f2)

// f1とf2に依存する処理
//
// f1, f2の2つのFutureが完了しないと処理が完了しない
go func(f1 *Future[int], f2 *Future[string]) {
	defer wg.Done()
	fmt.Printf("f1=%v\tf2=%v\n", f1.Get(), f2.Get())
}(f1, f2)

// 100ms後にf1に値を提供する
//
// このPromiseが値を提供するまで対応するFuture(f1)は結果を返さない
go func(p *Promise[int]) {
	time.Sleep(100 * time.Millisecond)
	p.Submit(999)
}(p1)

// 500ms後にf2に値を提供する
//
// このPromiseが値を提供するまで対応するFuture(f2)は結果を返さない
go func(p *Promise[string]) {
	time.Sleep(500 * time.Millisecond)
	p.Submit("hello world")
}(p2)

wg.Wait()
Output:

f1=999
f2=hello world
f1=999	f2=hello world

func (*Promise[T]) Submit

func (me *Promise[T]) Submit(v T)

Jump to

Keyboard shortcuts

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