美文网首页
Golang关闭需要结束的goroutine

Golang关闭需要结束的goroutine

作者: FredricZhu | 来源:发表于2019-06-14 09:06 被阅读0次
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    newRandStream := func(done <-chan interface{}) <-chan int {
        randStream := make(chan int)
        go func() {
            defer fmt.Println("randstream closeed, exited!")
            defer close(randStream)
            for {
                select {
                case randStream <- rand.Int():
                case <-done:
                    return
                }
            }
        }()
        return randStream
    }

    done := make(chan interface{})
    randStream := newRandStream(done)

    fmt.Println("Read 3 rand ints: ")
    for i := 1; i <= 3; i++ {
        fmt.Printf("%d %d \n", i, <-randStream)
    }

    close(done)
    time.Sleep(1 * time.Second)
}

程序输出如下,


image.png

相关文章

  • Golang关闭需要结束的goroutine

    程序输出如下,

  • golang channel 系统学习

    goroutine是个啥 使用golang的channel之前,我们需要先了解go的goroutine。Go 语言...

  • go学习笔记(四)——并发

    1. goroutine 什么是goroutine goroutine是golang的最小执行单元,每个go程序至...

  • go

    https://golang.google.cn/ goroutine简单示例 goroutine将结果通过cha...

  • goroutine 及channel

    本文主要介绍goroutine 和channel的使用。 基础知识介绍 goroutine 是 golang 中在...

  • Goroutine原理介绍

    为什么Golang需要单独开发一个Goroutine? 开销问题:POSIX的thread API虽然能够提供丰富...

  • Golang goroutine

    goroutine 是 Golang的最大卖点之一,它让并发编程变的十分简单,仅仅使用 go关键字就能快速的创建g...

  • Golang goroutine

    goroutine简介 goroutine是go语言中最为NB的设计,也是其魅力所在,goroutine的本质是协...

  • golang goroutine

    其实用go也用了一段时间,我是看视频入门的,然后去买书,反正来来回回用了一年多的时间,很多点知道怎么用,相关知识也...

  • goroutine and channel 2020-07-20

    参考:https://draveness.me/golang/docs goroutine and channel...

网友评论

      本文标题:Golang关闭需要结束的goroutine

      本文链接:https://www.haomeiwen.com/subject/honyfctx.html