zoukankan      html  css  js  c++  java
  • Go by Example: Non-Blocking Channel Operations

    原文:    https://gobyexample.com/non-blocking-channel-operations

    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.

    Here’s a non-blocking receive. If a value is available on messages then select will take the <-messages case with that value. If not it will immediately take the default case

    A non-blocking send works similarly. Here msg cannot be sent to the messages channel, because the channel has no buffer and there is no receiver. Therefore the default case is selected.

    We can use multiple cases above the default clause to implement a multi-way non-blocking select. Here we attempt non-blocking receives on both messages and signals.

    package main
    
    import "fmt"
    
    func main() {
        messages := make(chan string)
        signals := make(chan bool)
    
        select {
        case msg := <-messages:
            fmt.Println("received message", msg)
        default:
            fmt.Println("no message received")
        }
    
        msg := "hi"
        select {
        case messages <- msg:
            fmt.Println("sent message", msg)
        default:
            fmt.Println("no message sent")
        }
    
        select {
        case msg := <-messages:
            fmt.Println("received message", msg)
        case sig := <-signals:
            fmt.Println("received signal", sig)
        default:
            fmt.Println("no activity")
        }
    }
    

      

  • 相关阅读:
    Centos7安装nvidia显卡驱动
    Linux,Windows,Mac OS下换行的不同表示
    Linux权限管理问题
    Centos6.5final安装后若干问题与解决方法
    100天计划 绪
    python 变量,if,while,运算符
    python 初级重点
    py第四天
    搭建个人博客之路-01
    利用gulp+babel转es6
  • 原文地址:https://www.cnblogs.com/oxspirt/p/13985176.html
Copyright © 2011-2022 走看看