美文网首页
通道(Chanels)--协程交互(匿名函数)

通道(Chanels)--协程交互(匿名函数)

作者: bocsoft | 来源:发表于2018-12-03 16:50 被阅读0次

package main

import (
    "fmt"
    "time"
)

var strChan = make(chan string, 3)

func main() {
    syncChan1 := make(chan struct{}, 1)
    syncChan2 := make(chan struct{}, 2)
    go func() { // 用于演示接收操作
        <-syncChan1
        fmt.Println("Received a sync signal and wait a second...[receiver]")
        time.Sleep(time.Second)
        for {
            if elem, ok := <-strChan; ok {
                fmt.Println("Received:", elem, "[receiver]")
            } else {
                break
            }
        }
        fmt.Println("Stopped. [receiver]")
        syncChan2 <- struct{}{}
    }()

    go func() { //用于演示发送操作
        for _, elem := range []string{"a", "b", "c", "d"} {
            strChan <- elem
            fmt.Println("Sent:", elem, "[sender]")
            if elem == "c" {
                syncChan1 <- struct{}{}
                fmt.Println("Sent a sync signal. [sender]")
            }
        }
        fmt.Println("Wait 2 seconds...[sender]")
        time.Sleep(time.Second * 2)
        close(strChan)
        syncChan2 <- struct{}{}
    }()

    //如果下面两个语句都注释掉的化,程序会瞬间执行结束
    <-syncChan2
    <-syncChan2
}


// 输出 结果:
/*

Sent: a [sender]
Sent: b [sender]
Sent: c [sender]
Sent a sync signal. [sender]
Received a sync signal and wait a second...[receiver]
Received: a [receiver]
Received: b [receiver]
Sent: d [sender]
Wait 2 seconds...[sender]
Received: c [receiver]
Received: d [receiver]
Stopped. [receiver]

Process finished with exit code 0

 */




相关文章

  • 通道(Chanels)--协程交互(匿名函数)

  • 通道(Chanels)--协程交互(函数调用)

  • go - 学习笔记

    基础 函数 指针 结构体 接口 错误 协程 通道 基础 函数 指针 结构体 接口 错误 协程 通道

  • async/await协程语法

    协程函数(异步函数)使用async关键词将其变成协程方法 执行协程 协程函数执行结束时会抛出一个StopItera...

  • 关于Coroutine\Channel的几点注意

    通道,类似于go语言的chan,支持多生产者协程和多消费者协程。底层自动实现了协程的切换和调度。 实现原理 通道与...

  • 21. Go 协程

    21. Go 协程 Go 协程是什么? Go 协程是与其他函数或方法一起并发运行的函数或方法。Go 协程可以看作是...

  • kot

    #Kotlin之班门弄斧 ##面向对象 ##java和kotlin的交互 ##协程及协程框架 ## 面向对象 ...

  • go channel详解

    协程,通道 我们在普通程序中要执行代码如下代码 错误使用协程 由于没有调度,主协程率先执行完毕,代码执行已经关闭,...

  • python常用知识

    多线程,多进程,协程进程池 协程 字典 列表 函数 文件操作

  • Unity协程(Coroutine)

    协程与线程的区别 1、协程不是线程,也不是异步执行的。2、协程和 MonoBehaviour 的 Update函数...

网友评论

      本文标题:通道(Chanels)--协程交互(匿名函数)

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