You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/signal/cancel.go

52 lines
1007 B

package signal
8 years ago
import (
"sync"
)
9 years ago
// CancelSignal is a signal passed to goroutine, in order to cancel the goroutine on demand.
type CancelSignal struct {
cancel chan struct{}
8 years ago
done sync.WaitGroup
}
9 years ago
// NewCloseSignal creates a new CancelSignal.
func NewCloseSignal() *CancelSignal {
return &CancelSignal{
cancel: make(chan struct{}),
}
}
8 years ago
func (v *CancelSignal) WaitThread() {
v.done.Add(1)
8 years ago
}
9 years ago
// Cancel signals the goroutine to stop.
8 years ago
func (v *CancelSignal) Cancel() {
close(v.cancel)
}
8 years ago
func (v *CancelSignal) Cancelled() bool {
8 years ago
select {
8 years ago
case <-v.cancel:
8 years ago
return true
default:
return false
}
}
9 years ago
// WaitForCancel should be monitored by the goroutine for when to stop.
8 years ago
func (v *CancelSignal) WaitForCancel() <-chan struct{} {
return v.cancel
}
8 years ago
// FinishThread signals that current goroutine has finished.
8 years ago
func (v *CancelSignal) FinishThread() {
v.done.Done()
}
9 years ago
// WaitForDone is used by caller to wait for the goroutine finishes.
8 years ago
func (v *CancelSignal) WaitForDone() {
v.done.Wait()
}