Skip to content

Commit

Permalink
Make the add method thread safe
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Feb 2, 2019
1 parent 9cf633c commit bf07a0f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
7 changes: 6 additions & 1 deletion debounce.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2016 Bjørn Erik Pedersen <[email protected]>.
// Copyright © 2019 Bjørn Erik Pedersen <[email protected]>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
Expand All @@ -9,6 +9,7 @@
package debounce

import (
"sync"
"time"
)

Expand All @@ -26,11 +27,15 @@ func New(after time.Duration) func(f func()) {
}

type debouncer struct {
mu sync.Mutex
after time.Duration
timer *time.Timer
}

func (d *debouncer) add(f func()) {
d.mu.Lock()
defer d.mu.Unlock()

if d.timer != nil {
d.timer.Stop()
}
Expand Down
28 changes: 27 additions & 1 deletion debounce_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package debounce_test

import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
Expand Down Expand Up @@ -58,6 +59,31 @@ func TestDebounce(t *testing.T) {
}
}

func TestDebounceConcurrentAdd(t *testing.T) {
var wg sync.WaitGroup

var flag uint64

debounced := debounce.New(100 * time.Millisecond)

for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
debounced(func() {
atomic.CompareAndSwapUint64(&flag, 0, 1)
})
}()
}
wg.Wait()

time.Sleep(500 * time.Millisecond)
c := int(atomic.LoadUint64(&flag))
if c != 1 {
t.Error("Flag not set")
}
}

// Issue #1
func TestDebounceDelayed(t *testing.T) {

Expand All @@ -75,7 +101,7 @@ func TestDebounceDelayed(t *testing.T) {

debounced(f1)

time.Sleep(110 * time.Millisecond)
time.Sleep(200 * time.Millisecond)

c1 := int(atomic.LoadUint64(&counter1))
if c1 != 1 {
Expand Down

0 comments on commit bf07a0f

Please sign in to comment.