1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-04 21:15:24 +00:00
v2fly/common/signal/cancel.go

52 lines
1.0 KiB
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-18 20:30:03 +00:00
func (this *CancelSignal) WaitThread() {
this.done.Add(1)
}
2016-04-25 23:08:41 +00:00
// Cancel signals the goroutine to stop.
2016-04-25 16:39:30 +00:00
func (this *CancelSignal) Cancel() {
close(this.cancel)
}
2016-11-18 20:30:03 +00:00
func (this *CancelSignal) Cancelled() bool {
select {
case <-this.cancel:
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-04-25 16:39:30 +00:00
func (this *CancelSignal) WaitForCancel() <-chan struct{} {
return this.cancel
}
2016-11-18 20:30:03 +00:00
// FinishThread signals that current goroutine has finished.
func (this *CancelSignal) FinishThread() {
this.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-18 20:30:03 +00:00
func (this *CancelSignal) WaitForDone() {
this.done.Wait()
2016-04-25 16:39:30 +00:00
}