Add timeouts.

This commit is contained in:
Cody Soyland 2014-01-03 17:27:19 -06:00
parent 5a8456089c
commit 622b3b2351
2 changed files with 23 additions and 9 deletions

View file

@ -1,6 +1,11 @@
package hold
import "github.com/nu7hatch/gouuid"
import (
"errors"
"time"
"github.com/nu7hatch/gouuid"
)
type holdchan chan interface{}
type gethold struct {
@ -31,15 +36,24 @@ func (self *Holder) GetChan(id *uuid.UUID) holdchan {
return <-reply
}
func (self *Holder) Get(id *uuid.UUID) interface{} {
func (self *Holder) Get(id *uuid.UUID, timeout int) (interface{}, error) {
ch := self.GetChan(id)
return <-ch
select {
case val := <-ch:
return val, nil
case <-time.After(time.Duration(timeout) * time.Second):
self.DelChan(id)
return nil, errors.New("Timeout getting from holder")
}
}
func (self *Holder) Set(id *uuid.UUID, value interface{}) {
func (self *Holder) Set(id *uuid.UUID, value interface{}, timeout int) {
ch := self.GetChan(id)
go func() {
ch <- value
select {
case ch <- value:
case <-time.After(time.Duration(timeout) * time.Second):
}
self.DelChan(id)
}()
}

View file

@ -11,17 +11,17 @@ import (
func TestHoldChan(t *testing.T) {
Convey("set then get", t, func() {
id, _ := uuid.NewV4()
Hold.Set(id, "derp")
derp := Hold.Get(id)
Hold.Set(id, "derp", 10)
derp, _ := Hold.Get(id, 10)
So(derp, ShouldEqual, "derp")
})
Convey("get then set", t, func() {
id, _ := uuid.NewV4()
go func() {
time.Sleep(time.Second / 10)
Hold.Set(id, "derpsy")
Hold.Set(id, "derpsy", 10)
}()
derp := Hold.Get(id)
derp, _ := Hold.Get(id, 10)
So(derp, ShouldEqual, "derpsy")
})
}