栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Go语言:goroutine and channels

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go语言:goroutine and channels

channels 在Golang中是一个具有类型的管道(conduit)

Channels are a typed conduit through which you can send and receive values with the channel operator, <-.

创建管道的方式很简单:

ch := make(chan int)  // declare a channel of type int
ch := make(chan int, 100)  // buffered channels
// Sends to a buffered channel block only when the buffer is full. 
// Receives block when the buffer is empty.
v, ok := <-ch  // ok is false if there are no more values to receive and the channel is closed.

当所有的 gorountine 都处于 asleep 状态的时候,程序报错。

我感觉Golang里的 channels 就类似于Python标准库的queue.Queue,但是比Python要安全和智能。

关闭管道,使用close函数。

循环 for i := range c 从管道中接收值直到管道被关闭。

下面是一个例子:

一个线程不断生成 fibonacci 数列,另一个线程不断去输出,两个线程用 channels 通信
package main
import (
    "fmt"
)

func fibonacci(n int, c chan int) {
    x, y := 1, 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)
    for i := range c {
        fmt.Println(i)
    }
}

计算[0, 1000)的和,10个线程每个线程计算一部分,最后主线程计算总和。

package main

import "fmt"

func main() {
    c := make(chan int)
    for i := 0; i < 100; i += 10 {
        go func (a int, c chan int) {
            s := 0
            for i := a; i < a + 10; i++ {
                s += i
            }
            c <- s
        }(i, c)
    }
    sum, i := 0, 0
    for v := range c {
        sum += v
        i++
        if i == 10 {
            close(c)
        }
    }
    fmt.Println(sum)
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/657203.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号