golang之channel

Buffered Channels

package main

import "fmt"

func main() {
	ch := make(chan int, 2)
	ch <- 1
	ch <- 2
	fmt.Println(<-ch)
	fmt.Println(<-ch)
}

若是操做一個空的channel會怎麼樣呢?函數

package main

import "fmt"

func main() {
	ch := make(chan int, 2)
	ch <- 1
	ch <- 2
	fmt.Println(<-ch)
	fmt.Println(<-ch)

	v, ok := <-ch
	fmt.Println(v,ok)
}

1
2
fatal error: all goroutines are asleep - deadlock!spa

 

若是make函數不指定buffer length,會怎麼樣呢?線程

func main() {
	ch := make(chan int)
	ch <- 1
	fmt.Println(<-ch)
}

fatal error: all goroutines are asleep - deadlock!blog

 

上述例子中sender,receiver都是同一個線程。it

若是sender,receiver是不一樣線程會怎麼樣呢?class

package main

import "fmt"
import "time"

func WriteChannel(c chan int, v int) {
	fmt.Printf("write %d to channel\n", v)
	c <- v
}
func main() {
	c := make(chan int)
	
	go WriteChannel(c,1)
	fmt.Println(<-c)
	
	time.Sleep(100 * time.Millisecond)
	fmt.Printf("Done\n")
}

運行又正常了。import

相關文章
相關標籤/搜索