Skip to content

Commit d2ce2d9

Browse files
committed
✨ (concurrency): add concurrency chapter with goroutines and channels
1 parent 9d45729 commit d2ce2d9

File tree

4 files changed

+87
-1
lines changed

4 files changed

+87
-1
lines changed

README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,10 @@ copy(stockAmountByRangeClone, stockAmountByRange)
8383

8484
# 參考文件
8585

86-
[slice-intro](https://go.dev/blog/slices-intro)
86+
[slice-intro](https://go.dev/blog/slices-intro)
87+
88+
# install debug tool
89+
90+
```shell
91+
go install github.com/go-delve/delve/cmd/dlv@latest
92+
```

concurrency/REAME.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# concurrency
2+
3+
所謂的併發是指同時間處理多件事情的能力,但不一定是指同時一起進行。也就是可以透過類似 buffer 的方式來接收起來,然後透過一個 worker 逐步執行
4+
5+
## 說明
6+
7+
golang 採用 user level 的執行緒,並且由 goroutine scheduler 來分配執行任務給 os level 的執行序來執行
8+

concurrency/concurrency.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package concurrency
2+
3+
type WebsiteChecker func(string) bool
4+
5+
type result struct {
6+
string
7+
bool
8+
}
9+
10+
func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
11+
results := make(map[string]bool)
12+
resultChannel := make(chan result)
13+
for _, url := range urls {
14+
15+
go func() {
16+
// results[url] = wc(url)
17+
resultChannel <- result{
18+
url,
19+
wc(url),
20+
}
21+
}()
22+
}
23+
for range len(urls) {
24+
r := <-resultChannel
25+
results[r.string] = r.bool
26+
}
27+
return results
28+
}

concurrency/concurrency_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package concurrency
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
"time"
7+
)
8+
9+
func mockWebsiteChecker(url string) bool {
10+
return url != "waat://furhurerme.geds"
11+
}
12+
13+
func TestCheckWebsites(t *testing.T) {
14+
websites := []string{
15+
"http://google.com",
16+
"http://blog.gypsydave5.com",
17+
"waat://furhurerme.geds",
18+
}
19+
want := map[string]bool{
20+
"http://google.com": true,
21+
"http://blog.gypsydave5.com": true,
22+
"waat://furhurerme.geds": false,
23+
}
24+
25+
got := CheckWebsites(mockWebsiteChecker, websites)
26+
if !reflect.DeepEqual(want, got) {
27+
t.Fatalf("want %v, got %v", want, got)
28+
}
29+
}
30+
31+
func slowSubWebsiteChecker(_ string) bool {
32+
time.Sleep(20 * time.Millisecond)
33+
return true
34+
}
35+
36+
func BenchmarkCheckWebsites(b *testing.B) {
37+
urls := make([]string, 100)
38+
for i := 0; i < len(urls); i++ {
39+
urls[i] = "a url"
40+
}
41+
for b.Loop() {
42+
CheckWebsites(slowSubWebsiteChecker, urls)
43+
}
44+
}

0 commit comments

Comments
 (0)