Go ã§æéã®ãããå¦çã並åã§å®è¡ããã®ã« channel ã¨ããä»çµã¿ããããã¨ãç¥ã£ãã®ã§è©¦ãã¾ããã
Â
channel ã¨ã¯
goroutineéã§å¤ãéåä¿¡ããããã®æ©æ§ï¼ChatGPTããï¼ã
Â
Â
goroutine ã¯éåæã«å¦çã並è¡å®è¡ã§ãããã®ã®ãå¦çãçµäºããã¨ãã®ã¾ã¾ç ´æ£ããã¦ãã¾ãããã
éåæå¦çãè¡ã£ã¦ã¬ã¹ãã³ã¹ãããåããããå ´å㯠channel ã使ç¨ããå¿ è¦ãããããã§ãã
Â
以éã§ãã®å¦çãæ¤è¨¼ãã¾ãã
Â
æ¤è¨¼ç¨ã®ã³ã¼ããç¨æ
Â
ã·ã³ãã«ã«ã1ç§ã¹ãªã¼ããã¦æååãè¿ãé¢æ°ã§ãã
channelã使ããªãå ´åï¼åæï¼
Â
ãããå®è¡ããã¨ä¸è¨ã®çµæã§ãã
go run main.goÂ
finish 1
finish 2
finish 3
finish 4
finish 5
å¦çæéï¼ 5.068204847
Â
é ã«åæçã«å®è¡ãã¦ãããããå ¨ã¦å®è¡ããã®ã«ã«ã¼ãåæ°åãããã5ç§ãããã¾ããã
channelã使ãå ´åï¼éåæï¼
ç¶ãã¦ãchannel ã使ã£ã¦å¦çã並åå®è¡ããããã«ãã¦ã¿ã¾ãã
ä¸è¨ã®ããã«ã³ã¼ããæ¸ãæãã¾ããã
Â
Â
ï¼ã³ã¼ãã®è§£èª¬ï¼
WaitGroup ã使ç¨ãã¦ãgoroutine ãã¾ã¨ãã¦å®è¡ããããã«ãã¦ãã¾ãã
ä¸è¨ WaitGroup ã®èª¬æãæç²ããChatGPT ã§å訳â
A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.
Â
WaitGroup ã¯ãä¸é£ã®ã´ã«ã¼ãã³ã®çµäºãå¾ æ©ãã¾ããã¡ã¤ã³ã®ã´ã«ã¼ãã³ã¯ Add ãå¼ã³åºãã¦å¾ æ©ããã´ã«ã¼ãã³ã®æ°ãè¨å®ãã¾ãããã®å¾ãåã´ã«ã¼ãã³ãå®è¡ãããçµäºæã« Done ãå¼ã³åºãã¾ããåæã«ãWait ã使ç¨ãã¦ãã¹ã¦ã®ã´ã«ã¼ãã³ãçµäºããã¾ã§ãããã¯ãããã¨ãã§ãã¾ãã
Â
WaitGroup ã§goroutineãã¾ã¨ãã¦ä¸¦åå®è¡ãããã¨ãã§ããããã
並åå®è¡ããgoroutineããããã channel ã«å¤ãéä¿¡ããããã«ããæçµçã« channel ããå¤ãåãåºãå½¢ã«ãã¦ãã¾ãã
Â
heavyProcess é¢æ°
- defer wg.Done()㧠WaitGroup ã®å¾ æ©ã«ã¦ã³ãã1æ¸ãã
- channel ã«å¦ççµæãéä¿¡
main é¢æ°
- wg.Add(1) ã§Â WaitGroup ã®å¾ æ©ã«ã¦ã³ãã1å¢ãã
- go func ç¡åé¢æ°å ã® wg.Wait() 㧠WaitGroup ã®ãã¹ã¦ã® goroutine ãå®äºããã®ãå¾ ã¡åããããã¹ã¦å®äºããã channel ãéãã
- for å¥ã§ channel ããå¦ççµæãåå¾ã表示
ãããå®è¡ããã¨ä¸è¨ã®çµæã§ãã
go run main.goÂ
finish 5
finish 2
finish 3
finish 4
finish 1
å¦çæéï¼ 1.001226728
Â
åæå¦çã ã¨ç´5ç§ããã£ã¦ããã®ããchannelã使ã£ãéåæå¦çã ã¨ç´1ç§ã«ç縮ããã¾ããã
Â
以ä¸ãµã³ãã«ã§ãã
使ãããªããã°channelã¯å¼·åãªæ¦å¨ã«ãªãã®ã§ããã²ãã¹ã¿ã¼ãããã§ãã
Â