Skip to content

Commit

Permalink
feat: add signal
Browse files Browse the repository at this point in the history
  • Loading branch information
joway committed Mar 19, 2024
1 parent 6250b41 commit d28b329
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
63 changes: 63 additions & 0 deletions lang/channel/singal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package channel

import (
"context"
"time"
)

var (
_ Signal = (*sigal)(nil)
)

type Signal interface {
Signal()
Wait(ctx context.Context) bool
}

type SignalOption func(c *sigal)

func WithSinalTimeout(timeout time.Duration) SignalOption {
return func(s *sigal) {
s.timeout = timeout
}
}

func NewSignal(opts ...SignalOption) Signal {
sg := new(sigal)
for _, opt := range opts {
opt(sg)
}
sg.trigger = make(chan struct{})
return sg
}

type sigal struct {
trigger chan struct{}
timeout time.Duration
}

func (s *sigal) Signal() {
select {
case <-s.trigger:
default:
close(s.trigger)
}
}

func (s *sigal) Wait(ctx context.Context) bool {
if s.timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, s.timeout)
defer cancel()
}
if ctx == nil || ctx.Done() == nil {
<-s.trigger
return true
}
select {
case <-s.trigger:
return true
case <-ctx.Done():
return false
}
}
47 changes: 47 additions & 0 deletions lang/channel/singal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package channel

import (
"context"
"runtime"
"sync/atomic"
"testing"
"time"
)

func TestSignal(t *testing.T) {
sg := NewSignal()
var finished int32
emptyCtx := context.Background()
cancelCtx, cancelFunc := context.WithCancel(emptyCtx)
for i := 0; i < 10; i++ {
go func(i int) {
if i%2 == 0 {
sg.Wait(emptyCtx)
} else {
sg.Wait(cancelCtx)
}
atomic.AddInt32(&finished, 1)
}(i)
}
time.Sleep(time.Millisecond * 100)
cancelFunc()
for atomic.LoadInt32(&finished) != int32(5) {
runtime.Gosched()
}
sg.Signal()
for atomic.LoadInt32(&finished) != int32(10) {
runtime.Gosched()
}
}

func TestSignalTimeout(t *testing.T) {
sg := NewSignal(WithSinalTimeout(time.Millisecond * 200))
go func() {
time.Sleep(time.Millisecond * 500)
sg.Signal()
}()
begin := time.Now()
sg.Wait(context.Background())
cost := time.Since(begin)
t.Logf("cost=%dms", cost.Milliseconds())
}

0 comments on commit d28b329

Please sign in to comment.