go之select

简介: go之select

一、select超时检测

package csp
 
import (
  "fmt"
  "testing"
  "time"
)
 
func service() string {
  time.Sleep(time.Millisecond * 50)
  return "Done"
}
 
//异步 chan在go中是一个通道有可读可写的chan,也存在只读只写的chan 异步返回
func AsyncService() chan string {
  //创建接受通道
  retCh := make(chan string, 1)
  go func() {
    ret := service()
    fmt.Println("returned result.")
    //chan放数据
    retCh <- ret
    fmt.Println("service exited.")
  }()
  return retCh
}
 
//多路选择、超时
func TestSelect(t *testing.T) {
  //使用select监听
  select {
  case ret := <-AsyncService():
    t.Log(ret)
  //  设置超时等待
  case <-time.After(time.Millisecond * 100):
    t.Error("time out")
 
  }
}
超时设置为100的执行
=== RUN   TestSelect
returned result.
service exited.
    select_test.go:33: Done
--- PASS: TestSelect (0.06s)
PASS
超时设置为50
=== RUN   TestSelect
returned result.
service exited.
    select_test.go:36: time out
--- FAIL: TestSelect (0.06s)
 
FAIL

二、channel生产者与消费者

package csp
 
import (
  "fmt"
  "sync"
  "testing"
)
 
//生产者
func dataProducer(ch chan int, wg *sync.WaitGroup) {
  go func() {
    for i := 0; i < 10; i++ {
      //给通道添加数据
      ch <- i
    }
    //关闭channel,向关闭的channel发送数据,会导致panic
    close(ch)
    //ch <- -1 //panic: send on closed channel
    wg.Done()
  }()
}
 
//消费者
func dataReceiver(ch chan int, wg *sync.WaitGroup) {
  go func() {
    for {
      //从通道取数据,ok为bool值,true表示正常接收,false表示通道关闭
      //关闭通道,接收数据,返回零值
      if data, ok := <-ch; ok {
        fmt.Println(data)
      } else {
        break
      }
    }
    wg.Done()
  }()
}
 
func TestCloseChannel(t *testing.T) {
  var wg sync.WaitGroup
  //创建通道
  ch := make(chan int)
  wg.Add(1)
  //生成数据
  dataProducer(ch, &wg)
  wg.Add(1)
  //消费数据
  dataReceiver(ch, &wg)
  wg.Add(1)
  //消费数据
  dataReceiver(ch, &wg)
  wg.Wait()
}
=== RUN   TestCloseChannel
0
1
2
3
4
5
6
7
8
9
--- PASS: TestCloseChannel (0.00s)
PASS
目录
相关文章
|
2月前
|
程序员 Go
Golang深入浅出之-Select语句在Go并发编程中的应用
【4月更文挑战第23天】Go语言中的`select`语句是并发编程的关键,用于协调多个通道的读写。它会阻塞直到某个通道操作可行,执行对应的代码块。常见问题包括忘记初始化通道、死锁和忽视`default`分支。要解决这些问题,需确保通道初始化、避免死锁并添加`default`分支以处理无数据可用的情况。理解并妥善处理这些问题能帮助编写更高效、健壮的并发程序。结合使用`context.Context`和定时器等工具,可提升`select`的灵活性和可控性。
36 2
|
2月前
|
供应链 Go
掌握Go语言:利用Go语言的单向通道和select语句,提升库存管理效率(21)
掌握Go语言:利用Go语言的单向通道和select语句,提升库存管理效率(21)
|
2月前
|
Go
Go并发编程:玩转select语句
Go并发编程:玩转select语句
32 0
Go并发编程:玩转select语句
|
7月前
|
Go
go 缓冲区循环 以及 select选择
go 缓冲区循环 以及 select选择
30 0
Go中select条件语句详解
Go中select条件语句详解
141 0
|
Go
学会 Go select 语句,轻松实现高效并发
本文主要介绍了 `Go` 语言中的 `select` 语句。先是介绍语法,然后根据示例介绍了基本用法,接着介绍与channel结合使用的场景,最后总结使用的注意事项。
213 0
go里的select特点|Go主题月
在go中有一个类似switch的关键字,那就是select。 select的每个case接收的是I/O通讯操作,不能有其他表达式。select要配合channel使用。
104 0
讲透Go中的并发接收控制结构select
讲透Go中的并发接收控制结构select
Go面试题进阶知识点:select和channel
这篇文章将重点讲解Go面试进阶知识点:select和channel。
178 0
Go面试题进阶知识点:select和channel
|
存储 缓存 Go
Go-并发编程基础(goroutine、channel、select等)
Go-并发编程基础(goroutine、channel、select等)
101 0
Go-并发编程基础(goroutine、channel、select等)