Home > Backend Development > Golang > About typical usage of golang select

About typical usage of golang select

藏色散人
Release: 2021-05-08 11:56:26
forward
2000 people have browsed it

The following is the tutorial column of golang to introduce you to the typical usage of golang select. I hope it will be helpful to friends in need!

About typical usage of golang select

##code

package main

import (
    "fmt"
    "time"
)

func chanTest(ch chan int) {

    for { //select外层需要循环        select {        case value, ok := <-ch:
            fmt.Println(value, ok, time.Now())            if ok == false {
                fmt.Println("chan已经关闭", time.Now()) //select要自己判断退出,如果是for..range 形式,在读取完了关闭的chanel后,退出循环
                return
            }        default:
            fmt.Println("chan 空了", time.Now())            time.Sleep(time.Second * 5) //分支的处理会阻塞整个select
        }
    }
}

func main() {

    var ch = make(chan int, 100)    go chanTest(ch)

    ch <- 1
    ch <- 2
    time.Sleep(time.Second * 2)
    ch <- 3
    ch <- 4

    time.Sleep(time.Second)    close(ch)    for {        time.Sleep(time.Second)
    }
}
Copy after login

It should be noted that select The defalut will discard the data. When the chan is full, the data entering the chan will be discarded

The above is the detailed content of About typical usage of golang select. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template