golangã®ãã£ã³ãã«ã§ã»ããã©çãªããã«
mattnããã®ã¨ã³ããªã«è§¦çºããã¦ãææã§ä½¿ç¨ããã¡ãã£ã¨å¤ãã£ãgolangã®ãã£ã³ãã«ã®ä½¿ãæ¹ããç´¹ä»ãã¾ãã
ç¹å®ã®å¦çã®ä¸¦å度ãããç¨åº¦ã¾ã§ã«æããããã¿ãããªã³ãããã¾ãããï¼
ä¾ãã°CPUããã¼ãªå¦çã®ä¸¦åæ°ãããã ãã³ã¢æ°ãããã¾ã§ã«æããããã¨ãã
ãããªã¨ãã¯ãããã¡ä»ããã£ã³ãã«ãç¨æãã¦ããã¦ãå½è©²å¦çã®åå¾ã§ãã®ãã£ã³ãã«ã«write/readããããã¨ã§ãã»ããã©çãªå¶å¾¡ãã§ãã¾ãã
以ä¸ã®ãããªã«ã³ã¸ã§ãã
package main import ( "fmt" "sync" "time" ) var ch chan int = make(chan int, 4) // 並å度ã4ã«å¶é func heavyFunc(i int) { ch <- 1 // ãã£ã³ãã«ã®ãããã¡ãã¤ããã¤ã«ãªã£ã¦ãããããããã¯ãã defer func() { <-ch }() fmt.Println("start:", i) time.Sleep(time.Second) fmt.Println("end:", i) } func main() { wg := sync.WaitGroup{} for i := 0; i < 20; i++ { wg.Add(1) go func(i int) { heavyFunc(i) wg.Done() }(i) } wg.Wait() }
並åæ°ãä¸éã«éãã¦ããéã«ãããã¯ãããããªãå ´åã¯ãã¡ãã£ã¨å¤ãã¦ä»¥ä¸ã®ãããªã«ã³ã¸ã«ããã¨è¯ãã§ãã
func heavyFunc(i int) error { if len(ch) == cap(ch) { // ãããã¡ãã¤ããã¤ã ã£ãããã£ãã¨errorãè¿ã return errors.New("too busy!") } ch <- 1 defer func() { <-ch }() fmt.Println("start:", i) time.Sleep(time.Second) fmt.Println("end:", i) return nil }
(追è¨ãã¿ã¦ãã ãã)
å³å¯ã«ã¯len/capã®ãã§ãã¯ãåæã«ãããæããgoroutineãããã¨ãããã¯ãã¦ãã¾ãå¯è½æ§ãããã¾ãã
åé¿ããã«ã¯ãããªãåæå¦çãå¿
è¦ã«ãªãã¾ãâ¦â¦ãã©ãããã¾ã§ããå¿
è¦ãããã±ã¼ã¹ã¯å°ãªãããããªãããªãâ¦â¦ã¨ã
ä½è«ã§ããã©ããã使ãã¨ãã«ä¸¦åæ°ãã³ã¢æ°ããå°ãªãã«è¨å®ãã¡ããã¨ãçµæçã«CPUã使ãåããªããªãã®ã§
- 並åæ°ã¯ã³ã¢æ°
- GOMAXPROCSã¯ã³ã¢æ°ããå°ãå¤ã
ã¨ãã¦ããã¨éãå¦çã§CPUããã«ã§ä½¿ãã¤ã¤ãå¹³è¡ãã¦ãã以å¤ã®å¦çãç´°ã ã¨å¦çã§ããã¨ããç¶æ³ãä½ãã¾ãã
ãã¡ãããã¯ä»¥ä¸ã§ãã
2016-07-07 追è¨
golangã®ãã£ã³ãã«ã§ã»ããã©çãªããã« - okzkã¡ã¢b.hatena.ne.jplen==capã®ã¨ããã¯ãhttps://play.golang.org/p/CBvBeQ-jO8 ã®ããã« select ã使ãã¨raceãçºçããªãããããªãããª
2016/07/07 10:38
ä¸è¨ã³ã¡ã³ãã®Playgroundã®ãªã³ã¯ã§ãã
( ï¾Ð´ï¾)ï¾ï½¯!
channelã®writeæã«ãselect使ããã£ã¦ç¥ãã¾ããã§ããï¼ ãããã¨ããããã¾ãï¼ï¼ï¼
ã¡ãªã¿ã«ããã£ã¨è«¦ãã¦ã¨ã©ã¼ãè¿ãã¤ãã§ããã©ãWeb APIã¿ãããªã®ã§503 Service Temporarily Unavailable è¿ãã®ã«ä½¿ã£ããã¨ããã¾ãã
ãã£ã¨ä½ãããã°ããã¯ãã¬ãã·ã£ã¼å¶å¾¡ãã§ããããããã¾ãããã夢ã²ããããã