doujiang1913 2018-09-17 07:30
浏览 39
已采纳

close(channel)用于实现观察者模式

I need to stop an HTTP server on demand besides calling other functions as well when receiving the "quit" signal in no specific order.

In my try to implement something like the observer pattern, I found "handy" to create a channel (quit := make(chan struct{}), let's say the "subject" and then on each of the goroutines "observers" listen on that channel <-quit waiting until a change for then to continue.

The way I trigger all the functions at once is by closing the channel close(quit) not by writing into it, I have tried this and so far working, but wondering if there are some cons with this approach or if there are better/idiomatic ways of implementing similar behavior/pattern.

package main

import (
    "log"
    "net/http"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup

    srv := &http.Server{Addr: ":8080"}

    wg.Add(1)
    go func() {
        log.Println(srv.ListenAndServe())
        wg.Done()
    }()

    quit := make(chan struct{})
    go func() {
        <-quit
        if err := srv.Close(); err != nil {
            log.Printf("HTTP server Shutdown: %v", err)
        }
    }()

    wg.Add(1)
    go func() {
        <-quit
        log.Println("just waiting 1")
        wg.Done()
    }()

    wg.Add(1)
    go func() {
        <-quit
        log.Println("just waiting 2")
        wg.Done()
    }()

    <-time.After(2 * time.Second)
    close(quit)
    wg.Wait()
}

https://play.golang.org/p/uIfMJfN6xQy

  • 写回答

1条回答 默认 最新

  • doulu8341 2018-09-17 07:37
    关注

    I would say your way is good enough but lacks some elegance.

    You could implement required behavior using sync.Cond:

    https://golang.org/pkg/sync/#Cond
    How to correctly use sync.Cond?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵