设为首页 加入收藏

TOP

GO的并发之道-Goroutine调度原理&Channel详解(四)
2019-09-03 02:42:22 】 浏览:132
Tags:并发 -Goroutine 调度 原理 &Channel 详解
= make(chan int, 20) //任务管道 resch := make(chan int, 20) //结果管道 exitch := make(chan bool, 5) //退出管道 go func() { for i := 0; i < 10; i++ { taskch <- i } close(taskch) }() for i := 0; i < 5; i++ { //启动5个goroutine做任务 go Task(taskch, resch, exitch) } go func() { //等5个goroutine结束 for i := 0; i < 5; i++ { <-exitch } close(resch) //任务处理完成关闭结果管道,不然range报错 close(exitch) //关闭退出管道 }() for res := range resch{ //打印结果 fmt.Println("task res:",res) } } View Code

只读channel和只写channel

一般定义只读和只写的管道意义不大,更多时候我们可以在参数传递时候指明管道可读还是可写,即使当前管道是可读写的。

package main

import (
    "fmt"
    "time"
)

//只能向chan里写数据
func send(c chan<- int) {
    for i := 0; i < 10; i++ {
        c <- i
    }
}
//只能取channel中的数据
func get(c <-chan int) {
    for i := range c {
        fmt.Println(i)
    }
}
func main() {
    c := make(chan int)
    go send(c)
    go get(c)
    time.Sleep(time.Second*1)
}
//结果
0
1
2
3
4
5
6
7
8
9
View Code  

select-case实现非阻塞channel

原理通过select+case加入一组管道,当满足(这里说的满足意思是有数据可读或者可写)select中的某个case时候,那么该case返回,若都不满足case,则走default分支。

package main

import (
    "fmt"
)

func send(c chan int)  {
    for i :=1 ; i<10 ;i++  {
     c <-i
     fmt.Println("send data : ",i)
    }
}

func main() {
    resch := make(chan int,20)
    strch := make(chan string,10)
    go send(resch)
    strch <- "wd"
    select {
    case a := <-resch:
        fmt.Println("get data : ", a)
    case b := <-strch:
        fmt.Println("get data : ", b)
    default:
        fmt.Println("no channel actvie")

    }

}

//结果:get data :  wd
View Code

channel中定时器的使用

在对channel进行读写的时,可以对读写进行频率控制,通过time.Ticke实现

示例:

package main

import (
    "time"
    "fmt"
)

func main(){
    requests:= make(chan int ,5)
    for i:=1;i<5;i++{
        requests<-i
    }
    close(requests)
    limiter := time.Tick(time.Second*1)
    for req:=range requests{
        <-limiter
        fmt.Println("requets",req,time.Now()) //执行到这里,需要隔1秒才继续往下执行,time.Tick(timer)上面已定义
    }
}
//结果:
requets 1 2018-07-06 10:17:35.98056403 +0800 CST m=+1.004248763
requets 2 2018-07-06 10:17:36.978123472 +0800 CST m=+2.001798205
requets 3 2018-07-06 10:17:37.980869517 +0800 CST m=+3.004544250
requets 4 2018-07-06 10:17:38.976868836 +0800 CST m=+4.000533569
View Code

 

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Go语言(一) 环境的搭建 下一篇写给新手的 Go 开发指南

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目