Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Would be nice to have Running() and Terminating() #19

Open
arvenil opened this issue Oct 9, 2017 · 0 comments
Open

Would be nice to have Running() and Terminating() #19

arvenil opened this issue Oct 9, 2017 · 0 comments

Comments

@arvenil
Copy link

arvenil commented Oct 9, 2017

Consider below pseudo code

type Job struct {
    tomb *tomb.Tomb
}

func (j *Job) Start() error {
    if j.tomb.Alive() {
        return errors.New("job is still running")
    }
    j.tomb = &tomb.Tomb{}
    j.tomb.Go()
}

I want to create service that has long running goroutine, but only one, above code is not safe because Alive() can return false when tomb is in Dying state. So, I would like to know if tomb is Running (so dying or alive) or not. And there doesn't seem to be a way to actually do this with tomb.

I could read Dead() chan, but this would work only when tomb died, but if it never was started then it would hang forever as it is initialized as open chan.

Easy way would be something like this:

func (t *Tomb) Running() bool {
	t.m.Lock()
	defer t.m.Unlock()
	return t.alive > 0
}

Terminating() would be also useful since we don't always wait on channels in goroutines, but this can be easily done even without modifications to tomb.

func (t *Tomb) Terminating() bool {
        select {
            case <-t.dying:
                return true
            default:
                return false 
        }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant