Go语言struct{}类型的channel

版权声明:博客仅作为博主的个人笔记,未经博主允许不得转载。 https://blog.csdn.net/qq_35976351/article/details/82026108

简介

在Go语言中,有一种特殊的struct{}类型的channel,它不能被写入任何数据,只有通过close()函数进行关闭操作,才能进行输出操作。。struct类型的channel不占用任何内存!!!
定义:

var sig = make(chan struct{})

解除方式:

package main

func main() {
    var sig = make(chan struct{})
    close(sig)   // 必须进行close,才能执行<-sig,否则是死锁
    <-sig
}

应用

等待某任务的结束:

done := make(chan struct{})
go func() { 
  doLongRunningThing()
  close(done)
}()
// do some other bits
// wait for that long running thing to finish
<-done
// do more things

有很多方式可以完成这种操作,这是其中一个。。

同一时刻启动多个任务:

start := make(chan struct{})
for i := 0; i < 10000; i++ {
  go func() {
    <-start // wait for the start channel to be closed
    doWork(i) // do something
 }()
}
// at this point, all goroutines are ready to go - we just need to 
// tell them to start by closing the start channel
close(start)

这是真正意义上的同一时刻,不再是并发,是并行。。。

停止某事件:

loop:
for {
  select {
  case m := <-email:
    sendEmail(m)
  case <-stop: // triggered when the stop channel is closed
    break loop // exit
  }
}

一旦关闭了stop,整个循环就会终止。这在Golang的官方包io.pipe中有应用

参考博客

https://medium.com/@matryer/golang-advent-calendar-day-two-starting-and-stopping-things-with-a-signal-channel-f5048161018

猜你喜欢

转载自blog.csdn.net/qq_35976351/article/details/82026108