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

concurrency chapter #10

Closed
wants to merge 1 commit into from
Closed
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
28 changes: 28 additions & 0 deletions concurrency/concurrency.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package concurrency

type (
WebsiteChecker func(string) bool

result struct {
string
bool
}
)

func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
results := make(map[string]bool)
resultChannel := make(chan result)

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

for i := 0; i < len(urls); i++ {
r := <-resultChannel
results[r.string] = r.bool
}

return results
}
51 changes: 51 additions & 0 deletions concurrency/concurrency_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package concurrency

import (
"reflect"
"testing"
"time"
)

func slowStubWebsiteChecker(_ string) bool {
time.Sleep(20 * time.Millisecond)
return true
}

func BenchmarkCheckWebsites(b *testing.B) {
urls := make([]string, 100)
for i := 0; i < len(urls); i++ {
urls[i] = "url"
}

b.ResetTimer()
for i := 0; i < b.N; i++ {
CheckWebsites(slowStubWebsiteChecker, urls)
}
}

func mockWebsiteChecker(url string) bool {
if url == "waat://furhurterme.geds" {
return false
}
return true
}

func TestCheckWebsites(t *testing.T) {
websites := []string{
"http://google.com",
"http://blog.gypsydave5.com",
"waat://furhurterme.geds",
}

want := map[string]bool{
"http://google.com": true,
"http://blog.gypsydave5.com": true,
"waat://furhurterme.geds": false,
}

got := CheckWebsites(mockWebsiteChecker, websites)

if !reflect.DeepEqual(want, got) {
t.Fatalf("wanted %v, got %v", want, got)
}
}
Loading