Golang并发编程之channel的遍历

golang并发编程之channel的遍历


如果接受的量超出了通道的数据量就会报错,出现死锁

package main

import "fmt"

var c = make(chan int)

func main() {
	go func() {
		for i := 0; i < 2; i++ {
			c <- i
		}
		// close(c)
	}()
	a := <-c
	fmt.Printf("a: %v\n", a)
	a = <-c
	fmt.Printf("a: %v\n", a)
	a = <-c
	fmt.Printf("a: %v\n", a)
}

运行结果:

a: 0
a: 1
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
	c:/Users/79120/Desktop/GoPro/mypro/tempCodeRunnerFile.go:17 +0x119
exit status 2

加上close()关闭通道后,如果读不到就会输出默认值0,结构体为nil


1.使用for循环遍历

package main

import "fmt"

var c = make(chan int)

func main() {
	go func() {
		for i := 0; i < 5; i++ {
			c <- i
		}
		close(c)
	}()
	for {
		v, ok := <-c
		if ok {
			fmt.Printf("v: %v\n", v)
		} else {
			break
		}
	}
}

运行结果:

v: 0
v: 1
v: 2
v: 3
v: 4

或者

package main

import "fmt"

var c = make(chan int)

func main() {
	go func() {
		for i := 0; i < 5; i++ {
			c <- i
		}
		close(c)
	}()
	for i := 0; i < 3; i++ {
		r := <-c
		fmt.Printf("r: %v\n", r)
	}
}

运行结果:

r: 0
r: 1
r: 2

2.for range

package main

import "fmt"

var c = make(chan int)

func main() {
	go func() {
		for i := 0; i < 5; i++ {
			c <- i
		}
		close(c)
	}()
	for v := range c {
		fmt.Printf("v: %v\n", v)
	}
}

输出结果:

v: 0
v: 1
v: 2
v: 3
v: 4

你可能感兴趣的:(golang,c++,java)