Skip to content

Commit

Permalink
added Done method
Browse files Browse the repository at this point in the history
  • Loading branch information
sebogh@qibli.net authored and sebogh@qibli.net committed Feb 14, 2021
1 parent 492c7a1 commit 21c53da
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 11 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,16 @@ func main() {
// creating the new resource
r := updatingresource.NewUpdatingResource("-", f, 500 * time.Millisecond)

// query the resource 6 times
for i := 0; i <6; i++{
// query the resource 8 times
for i := 0; i <8; i++{
time.Sleep(200 * time.Millisecond)
x := r.Get().(string)
fmt.Printf("%s\n", x)

// stop updating after the 6th time
if i == 6 {
r.Done()
}
}
}
~~~~
11 changes: 9 additions & 2 deletions example_basic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,16 @@ func Example() {
// creating the new resource
r := updatingresource.NewUpdatingResource("-", f, 500 * time.Millisecond)

// query the resource 6 times
for i := 0; i <6; i++{
// query the resource 8 times
for i := 0; i <8; i++{
time.Sleep(200 * time.Millisecond)
x := r.Get().(string)
fmt.Printf("%s\n", x)

// stop updating after the 6th time
if i == 6 {
r.Done()
}
}

// Output:
Expand All @@ -31,4 +36,6 @@ func Example() {
// --
// ---
// ---
// ---
// ---
}
25 changes: 18 additions & 7 deletions updatingresource.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,41 @@ import (
type UpdatingResource struct {
mu *sync.RWMutex
x *interface{}
done chan bool
}

// NewUpdatingResource creates a new UpdatingResource. Thereby, f is the function
// that will be called every ttl to compute a new value for x (i.e. x=f(x)).
func NewUpdatingResource(x interface{}, f func(x interface{}) interface{}, ttl time.Duration) *UpdatingResource {
var mu sync.RWMutex
done := make(chan bool)
go func(f func(x interface{}) interface{}) {
ticker := time.NewTicker(ttl)
for {
<-ticker.C
y := f(x)
mu.Lock()
x = y
mu.Unlock()
select {
case <-done:
return
case <-ticker.C:
y := f(x)
mu.Lock()
x = y
mu.Unlock()
}
}
}(f)
resource := UpdatingResource{x: &x, mu: &mu}
resource := UpdatingResource{x: &x, mu: &mu, done: done}
return &resource
}

// Get returns the current value of the encapsulated object. Get is thread-safe
// Get returns the current value of the wrapped object. Get is thread-safe
// wrt. to the function updating the encapsulated object.
func (r *UpdatingResource) Get() interface{} {
r.mu.RLock()
defer r.mu.RUnlock()
return *r.x
}

// Done stops the updating of the wrapped object.
func (r *UpdatingResource) Done() {
r.done <- true
}

0 comments on commit 21c53da

Please sign in to comment.