Skip to content

Instantly share code, notes, and snippets.

View jonbodner's full-sized avatar

Jon Bodner jonbodner

  • @jonbodner@noc.social
View GitHub Profile
func DoSomething(f Foo) {
fmt.Println(f.A, f.B)
}
var x Foo
type Foo struct {
A int
B string
}
@jonbodner
jonbodner / client5.go
Created August 24, 2017 16:58
future-blog-post-18
func main() {
c, _ := context.WithTimeout(context.Background(), 1*time.Second)
a := 10
f := future.NewWithContext(c, func() (interface{}, error) {
return doSomethingThatTakesAWhile(a)
}).Then(func(v interface{}) (interface{}, error) {
return doAnotherThing(v.(int))
})
val, err := f.Get()
@jonbodner
jonbodner / new_context.go
Created August 24, 2017 16:56
future-blog-post-17
func NewWithContext(ctx context.Context, inFunc Process) Interface {
f := New(inFunc).(*futureImpl)
c := ctx.Done()
if c != nil {
go func() {
select {
case <-c:
//if context is cancelled, cancel future
f.Cancel()
case <-f.cancel:
@jonbodner
jonbodner / client4.go
Created August 24, 2017 16:52
future-blog-post-16
func main() {
a := 10
f := future.New(func() (interface{}, error) {
return doSomethingThatTakesAWhile(a)
}).Then(func(v interface{}) (interface{}, error) {
return doAnotherThing(v.(int))
})
go func() {
time.Sleep(1 * time.Second)
func New(inFunc Process) Interface {
return newInner(make(chan struct{}), &sync.Once{}, inFunc)
}
func newInner(cancelChan chan struct{}, o *sync.Once, inFunc Process) Interface {
f := futureImpl{
done: make(chan struct{}),
cancel: cancelChan,
o: o,
}
@jonbodner
jonbodner / futureImpl2.go
Created August 24, 2017 16:42
future-blog-post-14
type futureImpl struct {
done chan struct{}
cancel chan struct{}
val interface{}
err error
o *sync.Once
}
func (f *futureImpl) Cancel() {
select {
@jonbodner
jonbodner / future4.go
Created August 24, 2017 16:39
future-blog-post-13
// Interface represents a future. No concrete implementation is
// exposed; all access to a future is via this interface.
type Interface interface {
// Get returns the values calculated by the future. It will pause until
// the value is calculated.
//
// If Get is invoked multiple times, the same value will be returned each time.
// Subsequent calls to Get will return instantaneously.
//
// When the future is cancelled, nil is returned for both the value and the error.
@jonbodner
jonbodner / client3.go
Created August 24, 2017 16:35
future-blog-post-12
func main() {
a := 10
f := future.New(func() (interface{}, error) {
return doSomethingThatTakesAWhile(a)
}).Then(func(v interface{}) (interface{}, error) {
return doAnotherThing(v.(int))
})
// this will wait for a second to complete
// and will return nil for both val and err