mirror of
				https://github.com/yggdrasil-network/yggdrasil-go.git
				synced 2025-11-04 03:05:07 +03:00 
			
		
		
		
	add util.CancellationChild() and run gofmt
This commit is contained in:
		
							parent
							
								
									06e8403aaf
								
							
						
					
					
						commit
						6bf182e341
					
				
					 1 changed files with 60 additions and 49 deletions
				
			
		| 
						 | 
					@ -2,9 +2,9 @@ package util
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"errors"
 | 
						"errors"
 | 
				
			||||||
 | 
						"runtime"
 | 
				
			||||||
	"sync"
 | 
						"sync"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
  "runtime"
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type Cancellation interface {
 | 
					type Cancellation interface {
 | 
				
			||||||
| 
						 | 
					@ -63,14 +63,25 @@ func (c *cancellation) Error() error {
 | 
				
			||||||
	return err
 | 
						return err
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func CancellationWithTimeout(parent Cancellation, timeout time.Duration) Cancellation {
 | 
					func CancellationChild(parent Cancellation) Cancellation {
 | 
				
			||||||
	child := NewCancellation()
 | 
						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() {
 | 
						go func() {
 | 
				
			||||||
		timer := time.NewTimer(timeout)
 | 
							timer := time.NewTimer(timeout)
 | 
				
			||||||
		defer TimerStop(timer)
 | 
							defer TimerStop(timer)
 | 
				
			||||||
		select {
 | 
							select {
 | 
				
			||||||
    case <-parent.Finished():
 | 
							case <-child.Finished():
 | 
				
			||||||
      child.Cancel(parent.Error())
 | 
					 | 
				
			||||||
		case <-timer.C:
 | 
							case <-timer.C:
 | 
				
			||||||
			child.Cancel(errors.New("timeout"))
 | 
								child.Cancel(errors.New("timeout"))
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue