1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 10:08:15 -05:00
v2fly/common/signal/cancel.go

52 lines
1007 B
Go
Raw Normal View History

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