From e9803340156e2ddfb332b720f4191d60de71089b Mon Sep 17 00:00:00 2001 From: ookura keisuke Date: Wed, 22 Apr 2020 22:43:06 +0900 Subject: [PATCH] =?UTF-8?q?=E8=AA=B2=E9=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- goroutine/sleep_sort/main.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/goroutine/sleep_sort/main.go b/goroutine/sleep_sort/main.go index a04ea19..904f465 100644 --- a/goroutine/sleep_sort/main.go +++ b/goroutine/sleep_sort/main.go @@ -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) }