hic003cih / Golang

0 stars 0 forks source link

2020.06.12 早上golang學習心得(Go Channel 及 Goroutine 使用時機) #47

Open hic003cih opened 4 years ago

hic003cih commented 4 years ago

Go Channel 及 Goroutine 使用時機

Do not communicate by sharing memory; instead, share memory by communicating.

Communicating by sharing memory -> 使用goroutine會導致func內的變數被改變,然後下一個func就會抓到改變的變數了,要使用mux.Lock()和mux.Unlock()來確保變數不會被覆蓋

Share memory by communicating -> 使用channel,每次丟一個資料到channel,然後func 接收到channel的資料,channel空出來了,再將下一個資料丟到channel,後面使用一個 for 迴圈,陸續將 channle 裡面的值讀出來

hic003cih commented 4 years ago

https://blog.wu-boy.com/2020/01/when-to-use-go-channel-and-goroutine/