channel lock
channel ã§ãããã¯ãããããªã³ã¼ããæ¸ãããä¾ãã°ã¹ã¬ããã®ä¸¦åæ°ãå¶éãããã¨ããããããç°¡åãªç¨éã§ä½¿ãã®ã«åãåããããã
package main import ( "fmt" "time" ) func main() { go func() { for { fmt.Printf(".") time.Sleep(100 * time.Millisecond) } }() queue := make(chan int, 3) time.Sleep(1 * time.Second) queue <- 1 fmt.Println(1) time.Sleep(1 * time.Second) queue <- 2 fmt.Println(2) time.Sleep(1 * time.Second) queue <- 3 fmt.Println(3) go func() { time.Sleep(3 * time.Second) <-queue }() time.Sleep(1 * time.Second) // Lock queue <- 4 fmt.Println(4) }
0.1 ç§æ¯ã« .
ãåºåããã¦ã 1 ç§ãã¨ã« 1,2,3 ã¨åºåãã¦ãããqueue
ã¯3ã¤ã¾ã§è¨±å®¹ããã®ã§ã4ã¤ãã® Lock
ã®ã¨ãã㧠queue
ã« 4 ãéä¿¡ã§ããªãã¦ããã¯ããããã®ä¸ã«ãã goroutine 㧠3 ç§å¾ã« queue
ãã 1 ã¤åä¿¡ãã¦æ¨ã¦ãã¨ã 4 ãéä¿¡ã§ããããã«ãªã£ã¦åãã
åºåã¯ãããªæãã«ãªã
..........1 ..........2 ..........3 ..............................4
4 ã®ã¨ãã ã 3 ç§ããã¯ãã¦ãã®ãããããã¨ããã§ãã® queue
ããåä¿¡ããã³ã¼ãããªããã¨ã©ãã ãããã¤ãã§ã«éªéã ãã .
ãåºåãã¦ãã goroutine ããªããã¦ãã¾ããã
package main import ( "fmt" "time" ) func main() { queue := make(chan int, 3) time.Sleep(1 * time.Second) queue <- 1 fmt.Println(1) time.Sleep(1 * time.Second) queue <- 2 fmt.Println(2) time.Sleep(1 * time.Second) queue <- 3 fmt.Println(3) time.Sleep(1 * time.Second) queue <- 4 fmt.Println(4) }
ä¾å¤ãåºãã
1 2 3 fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan send]: main.main() /Users/rosylilly/tmp/go_channel_test/main.go:24 +0x22e exit status 2
å ¨é¨ã® goroutine ã å¯ã¦ã¦ãä½ããã¦ãªããããããããã¯ç¶æ ã ãã¨ãããã¨ãããããããããã¯æ¤ç¥ãã¦èªåã§æ»ã¬ãã¢ãã³ãªæãã ã