Skip to content

第10回の課題(大倉) #54

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
18 changes: 10 additions & 8 deletions goroutine/sleep_sort/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,24 @@ func main() {
// Channelは別の回でやるので、Goroutineだけで頑張る例
sortedNums := make([]int, 0, len(nums))

var wg sync.WaitGroup

for _, num := range nums {
// goroutineでは無名関数も使える
// ここでnumを渡す事で、forが進んでも各Goroutineのスコープ内でnは変化しない。
wg.Add(1)

go func(n int) {
// n秒スリープする
time.Sleep(time.Duration(n) * time.Second)
// mutexのLock
// 他のGoroutineからのアクセスがブロックされる
mu.Lock()
// deferで必ずUnlockする
defer mu.Unlock()

defer func() {
mu.Unlock()
wg.Done()
}()
sortedNums = append(sortedNums, n)
}(num) // (num)が無名関数の引数
}

time.Sleep(6 * time.Second)
wg.Wait()
fmt.Println(sortedNums)

}