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 已知平面坐标系(非直角坐标系)内三个点的坐标,反求两坐标轴的夹角
  • ¥15 webots有问题,无响应
  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上