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

Listen() has no stop mechanism. #41

Open
zvodd opened this issue Jun 25, 2021 · 0 comments
Open

Listen() has no stop mechanism. #41

zvodd opened this issue Jun 25, 2021 · 0 comments

Comments

@zvodd
Copy link

zvodd commented Jun 25, 2021

I ran into a problem where calling Stream.Close() causes a crash in my app.
The call was fine when the app was closing down. i.e. when other go routines being killed.
The reason, Stream.Listen() spawns a go routine with no exit feature, so it will keep polling the Stream even if it has been Closed. This of course results in a memory access violation.
I assume the reason testing hasn't picked this up before is because Steam.Close() is usually only called on exit.

I am using the following in my project to allow a stream to stop listening.
It's a slight API change adding a stop signal to Stream.Listen().
Though it might be a good idea to use the context package...

func (s *portmidi.Stream) Listen(stop <-chan int) <-chan portmidi.Event {
	const pollingInterval = 10 * time.Millisecond
	timer := time.NewTimer(pollingInterval)
	ch := make(chan portmidi.Event)
	go func(s *portmidi.Stream, ch chan portmidi.Event) {
		for {
			select {
			case <-timer.C:
				events, err := s.Read(1024)
				if err != nil {
					timer.Reset(pollingInterval)
					continue
				}
				for i := range events {
					ch <- events[i]
				}
				timer.Reset(pollingInterval)
			case <-stop:
				timer.Stop()
				return
			}
		}
	}(s, ch)
	return ch
}
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