Skip to content
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)

}