non-blocking channel options _ golang

Basic sends and receives on channels are blocking. However, we can use select with a default clause to implement non-blocking sends, receives, and even non-blocking multi-way selects

package main

import (
    "fmt"
)

func main() {

    message := make(chan string)
    signals := make(chan bool)

    select {
    case msg := <-message:
        fmt.Println("received message", msg)
    default:
        fmt.Println("no message received")
    }

    msg := "hi"

    select {
    case message <- msg:
        fmt.Println("sent message", msg)
    default:
        fmt.Println("no message sent")
    }

    select {
    case msg := <-message:
        fmt.Println("received message", msg)
    case sig := <-signals:
        fmt.Println("received signal", sig)
    default:
        fmt.Println("no activity")
    }

}
no message received
no message sent
no activity

总结 :

  1:....

本文来自:博客园

感谢作者:jackkiexu

查看原文:non-blocking channel options _ golang

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。