golang 中 channel 的非阻塞访问方法

在golang中,基本的channel读写操作都是阻塞的,如果你想要非阻塞的,可以使用如下示例:

即只要在select中加入default,阻塞立即变成非阻塞:

 

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")
    }
}

 

输出:

no message received
no message sent
no activity

 

 

注意,golang无法kill 一个 goroutine,你 #只能# 通过一个channel给它发送消息让它退出,示例如下:

quit := make(chan bool)
go func() {
    for {
        select {
        case <- quit:
            return
        default:
            // Do other stuff
        }
    }
}()

// Do stuff

// Quit goroutine
close(quit)

 

posted @ 2018-06-11 14:51  微信公众号--共鸣圈  阅读(2882)  评论(0编辑  收藏  举报