mirror of
https://github.com/yggdrasil-network/yggdrasil-go.git
synced 2024-12-24 16:57:53 +00:00
add util.CancellationChild() and run gofmt
This commit is contained in:
parent
06e8403aaf
commit
6bf182e341
@ -2,9 +2,9 @@ package util
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
type Cancellation interface {
|
||||
@ -49,7 +49,7 @@ func (c *cancellation) Finished() <-chan struct{} {
|
||||
|
||||
func (c *cancellation) Cancel(err error) error {
|
||||
select {
|
||||
case c.signal<-err:
|
||||
case c.signal <- err:
|
||||
return nil
|
||||
case <-c.cancel:
|
||||
return c.Error()
|
||||
@ -63,14 +63,25 @@ func (c *cancellation) Error() error {
|
||||
return err
|
||||
}
|
||||
|
||||
func CancellationWithTimeout(parent Cancellation, timeout time.Duration) Cancellation {
|
||||
func CancellationChild(parent Cancellation) Cancellation {
|
||||
child := NewCancellation()
|
||||
go func() {
|
||||
select {
|
||||
case <-child.Finished():
|
||||
case <-parent.Finished():
|
||||
child.Cancel(parent.Error())
|
||||
}
|
||||
}()
|
||||
return child
|
||||
}
|
||||
|
||||
func CancellationWithTimeout(parent Cancellation, timeout time.Duration) Cancellation {
|
||||
child := CancellationChild(parent)
|
||||
go func() {
|
||||
timer := time.NewTimer(timeout)
|
||||
defer TimerStop(timer)
|
||||
select {
|
||||
case <-parent.Finished():
|
||||
child.Cancel(parent.Error())
|
||||
case <-child.Finished():
|
||||
case <-timer.C:
|
||||
child.Cancel(errors.New("timeout"))
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user