v2ray-core/common/signal/cancel.go

52 lines
1007 B
Go
Raw Normal View History

2016-04-25 16:39:30 +00:00
package signal
2016-11-18 20:30:03 +00:00
import (
"sync"
)
2016-04-25 23:08:41 +00:00
// CancelSignal is a signal passed to goroutine, in order to cancel the goroutine on demand.
2016-04-25 16:39:30 +00:00
type CancelSignal struct {
cancel chan struct{}
2016-11-18 20:30:03 +00:00
done sync.WaitGroup
2016-04-25 16:39:30 +00:00
}
2016-04-25 23:08:41 +00:00
// NewCloseSignal creates a new CancelSignal.
2016-04-25 16:39:30 +00:00
func NewCloseSignal() *CancelSignal {
return &CancelSignal{
cancel: make(chan struct{}),
}
}
2016-11-27 20:39:09 +00:00
func (v *CancelSignal) WaitThread() {
v.done.Add(1)
2016-11-18 20:30:03 +00:00
}
2016-04-25 23:08:41 +00:00
// Cancel signals the goroutine to stop.
2016-11-27 20:39:09 +00:00
func (v *CancelSignal) Cancel() {
close(v.cancel)
2016-04-25 16:39:30 +00:00
}
2016-11-27 20:39:09 +00:00
func (v *CancelSignal) Cancelled() bool {
2016-11-18 20:30:03 +00:00
select {
2016-11-27 20:39:09 +00:00
case <-v.cancel:
2016-11-18 20:30:03 +00:00
return true
default:
return false
}
}
2016-04-25 23:08:41 +00:00
// WaitForCancel should be monitored by the goroutine for when to stop.
2016-11-27 20:39:09 +00:00
func (v *CancelSignal) WaitForCancel() <-chan struct{} {
return v.cancel
2016-04-25 16:39:30 +00:00
}
2016-11-18 20:30:03 +00:00
// FinishThread signals that current goroutine has finished.
2016-11-27 20:39:09 +00:00
func (v *CancelSignal) FinishThread() {
v.done.Done()
2016-04-25 16:39:30 +00:00
}
2016-04-25 23:08:41 +00:00
// WaitForDone is used by caller to wait for the goroutine finishes.
2016-11-27 20:39:09 +00:00
func (v *CancelSignal) WaitForDone() {
v.done.Wait()
2016-04-25 16:39:30 +00:00
}