From 095eed36f8799419ff300688e5d5af89e124f2f8 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Wed, 27 Jun 2018 17:42:09 -0700 Subject: [PATCH 1/2] add a Poll function to node promises (and improve the documentation) --- promise.go | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/promise.go b/promise.go index 02743b0..cb5c182 100644 --- a/promise.go +++ b/promise.go @@ -4,12 +4,8 @@ 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{}), @@ -17,6 +13,12 @@ func NewNodePromise(ctx context.Context) *NodePromise { } } +// 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 @@ -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. @@ -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. @@ -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) { + 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. From c01f809fab73b130d890a32c924aa3bd0e98db66 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Thu, 12 Jul 2018 10:45:52 +0200 Subject: [PATCH 2/2] don't block in poll --- promise.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/promise.go b/promise.go index cb5c182..c8c3e8d 100644 --- a/promise.go +++ b/promise.go @@ -54,12 +54,16 @@ func (np *NodePromise) Send(nd Node) { } // Poll returns the result of the promise if ready but doesn't block. +// +// Returns nil, nil if not ready. func (np *NodePromise) Poll() (Node, error) { select { case <-np.done: return np.value, np.err case <-np.ctx.Done(): return nil, np.ctx.Err() + default: + return nil, nil } }