Go语言并发与通道的运用

在go语言中我们可以使用goroutine 开启并发。
goroutine 是轻量级线程,goroutine 的调度是由 Golang 运行时进行管理的。
goroutine 语法格式:
go 函数名( 参数列表 )
实例1:

package main

import (
        "fmt"
        "time"
)

func say(s string) {
    
    
        for i := 0; i < 5; i++ {
    
    
                time.Sleep(100 * time.Millisecond)
                fmt.Println(s)
        }
}

func main() {
    
    
        go say("world")
        say("hello")
}

输出结果:

world
hello
hello
world
world
hello
hello
world
world
hello

我们通过以上程序发现输出结果是没有顺序的

通道(channel)

通道(channel)是用来传递数据的一个数据结构。
实例2:

package main

import "fmt"

func sum(s []int, c chan int) {
    
    
        sum := 0
        for _, v := range s {
    
    
                sum += v
        }
        c <- sum // 把 sum 发送到通道 c
}

func main() {
    
    
        s := []int{
    
    7, 2, 8, -9, 4, 0}

        c := make(chan int)
        go sum(s[:len(s)/2], c)
        go sum(s[len(s)/2:], c)
        x, y := <-c, <-c // 从通道 c 中接收

        fmt.Println(x, y, x+y)
}

输出结果:

-5 17 12

通道缓冲区

带缓冲区的通道允许发送端的数据发送和接收端的数据获取处于异步状态,就是说发送端发送的数据可以放在缓冲区里,等待接收端去获取数据,而不是立刻需要接收端去获取数据。
实例3:

package main

import "fmt"

func main() {
    
    
    // 这里我们定义了一个可以存储整数类型的带缓冲通道
        // 缓冲区大小为2
        ch := make(chan int, 2)

        // 因为 ch 是带缓冲的通道,我们可以同时发送两个数据
        // 而不用立刻需要去同步读取数据
        ch <- 1
        ch <- 2

        // 获取这两个数据
        fmt.Println(<-ch)
        fmt.Println(<-ch)
}

输出结果:

1
2

Go 遍历通道与关闭通道

实例4:

package main

import (
        "fmt"
)

func fibonacci(n int, c chan int) {
    
    
        x, y := 0, 1
        for i := 0; i < n; i++ {
    
    
                c <- x
                x, y = y, x+y
        }
        close(c)
}

func main() {
    
    
        c := make(chan int, 10)
        go fibonacci(cap(c), c)
        // range 函数遍历每个从通道接收到的数据,因为 c 在发送完 10 个
        // 数据之后就关闭了通道,所以这里我们 range 函数在接收到 10 个数据
        // 之后就结束了。如果上面的 c 通道不关闭,那么 range 函数就不
        // 会结束,从而在接收第 11 个数据的时候就阻塞了。
        for i := range c {
    
    
                fmt.Println(i)
        }
}

输出结果:

0
1
1
2
3
5
8
13
21
34

猜你喜欢

转载自blog.csdn.net/qq_43332010/article/details/120235503