当前位置:   article > 正文

Go语言struct{}类型的channel_chan struct

chan struct

简介

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

var sig = make(chan struct{})
  • 1

解除方式:

package main

func main() {
	var sig = make(chan struct{})
	close(sig)   // 必须进行close,才能执行<-sig,否则是死锁
	<-sig
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

应用

等待某任务的结束:

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

同一时刻启动多个任务:

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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

停止某事件:

loop:
for {
  select {
  case m := <-email:
    sendEmail(m)
  case <-stop: // triggered when the stop channel is closed
    break loop // exit
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

参考博客

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/907917
推荐阅读
相关标签
  

闽ICP备14008679号