我命由我,不由天!


  • 搜索
prometheus docker golang linux kubernetes

goroutine and channel

发表于 2021-01-06 | 分类于 golang | 0 | 阅读次数 284

goroutine超时处理

package main

import (
    "fmt"
    "time"
)

func main() {

    c1 := make(chan string, 1)
    go func() {
        time.Sleep(2 * time.Second)
        c1 <- "result 1"
    }()
    select {
    case res := <-c1:
        fmt.Println(res)
    case <-time.After(1 * time.Second):
        fmt.Println("timeout 1")
    }

    c2 := make(chan string, 1)
    go func() {
        time.Sleep(2 * time.Second)
        c2 <- "result 2"
    }()
    select {
    case res := <-c2:
        fmt.Println(res)
    case <-time.After(3 * time.Second):
        fmt.Println("timeout 2")
    }
}

无阻塞

select {
    case res := <-c2:
    	fmt.Println(res)
    case <-time.After(3 * time.Second):
    	fmt.Println("timeout 2")
    default:
    	fmt.Println("abc")
}

通道关闭

  1. close(channel) 关闭通道
  2. j,more := <- channel 如果已关闭,则more为 false
package main

import "fmt"

func main() {
    jobs := make(chan int, 5)
    done := make(chan bool)

    go func() {
        for {
            j, more := <-jobs
            if more {
                fmt.Println("received job", j)
            } else {
                fmt.Println("received all jobs")
                done <- true
                return
            }
        }
    }()

    for j := 1; j <= 3; j++ {
        jobs <- j
        fmt.Println("sent job", j)
    }
    close(jobs)
    fmt.Println("sent all jobs")

    <-done
}

管道遍历

package main

import "fmt"

func main() {
    queue := make(chan string, 2)
    queue <- "one"
    queue <- "two"
    close(queue)
    for elem := range queue {
        fmt.Println(elem)
    }
}

只读和只写管道

  • <-chan string 只读
  • chan<- string 只写
package main

import "fmt"


func test(jobs chan int, done chan bool) {
	for {
		j, more := <-jobs
		if more {
			fmt.Println("received job", j)
		} else {
			fmt.Println("received all jobs")
			done <- true
			return
		}
	}
}

func sendMsg(jobs chan int){
	for j := 1; j <= 3; j++ {
		jobs <- j
		fmt.Println("sent job", j)
	}
	close(jobs)
	fmt.Println("sent all jobs")
}


func main() {
	jobs := make(chan int, 5)
	done := make(chan bool)

	go test(jobs, done)
	go sendMsg(jobs)
	
	<-done
}

控制并发数

package main

import (
	"fmt"
	"sync"
	"time"
)

var wg = sync.WaitGroup{}

func main(){
	ch := make(chan int ,2)
	for i := 0; i < 100; i ++ {
		wg.Add(1)
		ch <- 1
		go func(ch chan int){
			defer wg.Done()
			time.Sleep( time.Second)
			fmt.Println(i)
			<- ch
		}(ch)
	}
	wg.Wait()
}
  • 本文作者: Dante
  • 本文链接: https://gaodongfei.com/archives/goroutineandchannel
  • 版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!
# golang
go-reflect
gRPC初学
  • 文章目录
  • 站点概览
Dante

Dante

119 日志
5 分类
5 标签
RSS
Creative Commons
0%
© 2023 Dante
由 Halo 强力驱动
|
主题 - NexT.Pisces v5.1.4
沪ICP备2020033702号