Skip to content

[WIP] 第11回Go勉強会の課題@luccafort #59

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

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
16 changes: 16 additions & 0 deletions channel/task/basic/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
package main

import (
"fmt"
"time"
)

// channel/basicのInt版
// Goroutine内で好きなIntをchannelを経由でMain Goroutineに渡し標準出力にPrintしてみる。
func main() {
ch := make(chan int, 0)
go func(n int) {
// いる?
time.Sleep(1 * time.Second)
// channelへの値の送信(`ch <-`の形式)
ch <- n
}(13)

recieved := <-ch
fmt.Println("recieved")
fmt.Println(recieved)
}
41 changes: 41 additions & 0 deletions channel/task/sleep_sort/main.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,45 @@
package main

import (
"fmt"
"sync"
"time"
)

// 受信専用channel, for range, close←を使ってSleepSortを実装する
func main() {
nums := []int{1, 3, 2, 5, 4}
sortedNums := []int{}

for v := range receivedChan(nums) {
fmt.Println(v)
sortedNums = append(sortedNums, v)
}
fmt.Println(sortedNums)
}

func receivedChan(nums []int) <-chan int {
count := len(nums)
ch := make(chan int, count)
go func(nums []int) {
defer close(ch)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

受信専用チャンネルだとクローズできなかった(送信側がクローズできるべきなのでそれはそう)ので関数に切り出してGoroutineするところで defer close() するようにした……がもうちょいなんかやりようがある気がする。

sleepSortCh(ch, nums)
}(nums)

return ch
}

func sleepSortCh(ch chan int, nums []int) chan int {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

引数にチャンネルを取ってるが依存してしまっているので依存しないようにしたいが考えつかなかった。

var wg sync.WaitGroup
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WaitGroupで実装したがerrgroup.Groupで実装したほうがよかったかも。

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

通常こういう処理を行うときって外部APIへの通信だったりするのでそのレスポンスを待ち受けるならエラーが返る可能性を考慮して errgroup.Group じゃないと駄目そう。

for _, num := range nums {
wg.Add(1)
go func(num int) {
defer wg.Done()
time.Sleep(time.Duration(num) * time.Second)
ch <- num
}(num)
}
wg.Wait()

return ch
}