Add SleepNotify, to notify a channel once the "waiter" is fully regis… #99
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
TLDR: Jump to the Solution section to see the working example.
In highly concurrent code, it is sometimes impossible to know how many "waiters" are going to be present at a certain time.
So I made a test where we want to ensure that in thread 1, the counter is incremented after a 1min sleep.
Another thread 2, will sometime create another Sleep, making it impossible to use
BlockUntilContextconsistently.First attempt with
BlockUntilContext(not working) ->So instead, I will close beforeCh just before the Sleep that I'm interested in, to advance the clock when the goroutine is ready to Sleep.
But this fails (sometimes) because the "waiter" is not yet registered when we close the
beforeChso we sometime advance the clock too early.(not working)
Solution is SleepNotify
SleepNotify will ensure that the "waiter" is registered before closing the "beforeCh" channel.
So we will only ever advance the clock when the thread we're interested in, is actually sleeping.
This is how you can run the 3 examples and see that only the last solution works
go test -race -count 10 -run TestSleepNotify