2020-01-08 19:51:21 +01:00
|
|
|
package mutex
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2022-09-28 09:01:17 +02:00
|
|
|
// Activity represents work that can be started and stopped.
|
|
|
|
type Activity struct {
|
2020-01-08 19:51:21 +01:00
|
|
|
busy bool
|
|
|
|
canceled bool
|
|
|
|
mutex sync.Mutex
|
|
|
|
}
|
|
|
|
|
2022-09-28 09:01:17 +02:00
|
|
|
// Running checks if the Activity is currently running.
|
|
|
|
func (b *Activity) Running() bool {
|
2020-01-08 19:51:21 +01:00
|
|
|
b.mutex.Lock()
|
|
|
|
defer b.mutex.Unlock()
|
|
|
|
|
|
|
|
return b.busy
|
|
|
|
}
|
|
|
|
|
2022-09-28 09:01:17 +02:00
|
|
|
// Start marks the Activity as started and returns an error if it is already running.
|
|
|
|
func (b *Activity) Start() error {
|
2020-01-08 19:51:21 +01:00
|
|
|
b.mutex.Lock()
|
|
|
|
defer b.mutex.Unlock()
|
|
|
|
|
|
|
|
if b.canceled {
|
|
|
|
return errors.New("still running")
|
|
|
|
}
|
|
|
|
|
|
|
|
if b.busy {
|
|
|
|
return errors.New("already running")
|
|
|
|
}
|
|
|
|
|
|
|
|
b.busy = true
|
|
|
|
b.canceled = false
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-09-28 09:01:17 +02:00
|
|
|
// Stop marks the Activity as stopped.
|
|
|
|
func (b *Activity) Stop() {
|
2020-01-08 19:51:21 +01:00
|
|
|
b.mutex.Lock()
|
|
|
|
defer b.mutex.Unlock()
|
|
|
|
|
|
|
|
b.busy = false
|
|
|
|
b.canceled = false
|
|
|
|
}
|
|
|
|
|
2022-09-28 09:01:17 +02:00
|
|
|
// Cancel requests to stop the Activity.
|
|
|
|
func (b *Activity) Cancel() {
|
2020-01-08 19:51:21 +01:00
|
|
|
b.mutex.Lock()
|
|
|
|
defer b.mutex.Unlock()
|
|
|
|
|
|
|
|
if b.busy {
|
|
|
|
b.canceled = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-28 09:01:17 +02:00
|
|
|
// Canceled marks the Activity as stopped.
|
|
|
|
func (b *Activity) Canceled() bool {
|
2020-01-08 19:51:21 +01:00
|
|
|
b.mutex.Lock()
|
|
|
|
defer b.mutex.Unlock()
|
|
|
|
|
|
|
|
return b.canceled
|
|
|
|
}
|