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

Fix racy shutdown logic #11

Merged
merged 1 commit into from
Oct 7, 2022
Merged

Fix racy shutdown logic #11

merged 1 commit into from
Oct 7, 2022

Conversation

Merovius
Copy link
Contributor

@Merovius Merovius commented Oct 7, 2022

There are two issues with the shutdown logic:

  1. If Close() is called before the eventLoop is scheduled, the WaitGroup counter is still 0 and Close does not wait for the eventLoop to finish. That's a race condition
  2. If Close() is called more than once, it panics, as the code tries to write to a closed channel. It is generally good practice to make Close idempotent, to allow the defer x.Close(); /* … */ return x.Close() idiom, which is a convenient way to guarantee both that Close is called and that the error is checked.

This commit fixes both and factors the shutdown logic into a new type for readability and ease of understanding.

There are two issues with the shutdown logic:
1. If Close() is called before the eventLoop is scheduled, the WaitGroup
   counter is still 0 and Close does not wait for the eventLoop to
   finish. That's a race condition
2. If Close() is called more than once, it panics, as the code tries to
   write to a closed channel. It is generally good practice to make
   Close idempotent, to allow the
   defer x.Close(); /* … */ return x.Close()
   idiom, which is a convenient way to guarantee both that Close is
   called *and* that the error is checked.

This commit fixes both and factors the shutdown logic into a new type
for readability and ease of understanding.
@esiqveland
Copy link
Owner

Hey, thank you. It is nicer that Close() is idempotent for the user.

@esiqveland esiqveland merged commit 5a5f426 into esiqveland:master Oct 7, 2022
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

Successfully merging this pull request may close these issues.

2 participants