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 reusing the url variable in concurrency tutorial #825

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions concurrency.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,8 +363,9 @@ func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
resultChannel := make(chan result)

for _, url := range urls {
u := url
go func() {
resultChannel <- result{url, wc(url)}
resultChannel <- result{u, wc(u)}
}()
}

Expand All @@ -385,7 +386,11 @@ The new type, `result` has been made to associate the return value of the
within the struct; this can be useful in when it's hard to know what to name
a value.

Now when we iterate over the urls, instead of writing to the `map` directly
Now when we iterate over the urls, at first, we create a copy of the `url`
variable as `u` and pass it to the goroutine. Without this step, all gorouties
will reuse the same `url` variable, leading to unreliable results.

Next, instead of writing to the `map` directly
we're sending a `result` struct for each call to `wc` to the `resultChannel`
with a _send statement_. This uses the `<-` operator, taking a channel on the
left and a value on the right:
Expand Down
3 changes: 2 additions & 1 deletion concurrency/v3/check_websites.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
resultChannel := make(chan result)

for _, url := range urls {
u := url
go func() {
resultChannel <- result{url, wc(url)}
resultChannel <- result{u, wc(u)}
}()
}

Expand Down