Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions promise.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@ import (
"context"
)

// NodePromise provides a promise like interface for a dag Node
// the first call to Get will block until the Node is received
// from its internal channels, subsequent calls will return the
// cached node.
//
// Thread Safety: This is multiple-consumer/single-producer safe.
// NewNodePromise constructs a NodePromise with the given context. Canceling the
// context will immediately cancel the NodePromise.
func NewNodePromise(ctx context.Context) *NodePromise {
return &NodePromise{
done: make(chan struct{}),
ctx: ctx,
}
}

// NodePromise provides a promise like interface for a dag Node
// the first call to Get will block until the Node is received
// from its internal channels, subsequent calls will return the
// cached node.
//
// Thread Safety: This is multiple-consumer/single-producer safe.
type NodePromise struct {
value Node
err error
Expand All @@ -25,7 +27,7 @@ type NodePromise struct {
ctx context.Context
}

// Call this function to fail a promise.
// Fail fails this promise.
//
// Once a promise has been failed or fulfilled, further attempts to fail it will
// be silently dropped.
Expand All @@ -38,7 +40,7 @@ func (np *NodePromise) Fail(err error) {
close(np.done)
}

// Fulfill this promise.
// Send fulfills this promise.
//
// Once a promise has been fulfilled or failed, calling this function will
// panic.
Expand All @@ -51,6 +53,16 @@ func (np *NodePromise) Send(nd Node) {
close(np.done)
}

// Poll returns the result of the promise if ready but doesn't block.
func (np *NodePromise) Poll() (Node, error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about the name.
poll (2) in Linux is blocking.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both java and rust use a poll function to check futures without waiting.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, interesting.

select {
case <-np.done:
return np.value, np.err
case <-np.ctx.Done():
return nil, np.ctx.Err()
}
}

// Get the value of this promise.
//
// This function is safe to call concurrently from any number of goroutines.
Expand Down