GOLANG的context和并发模型
GOLANG1.7新增了context,最初这个package是在 对context的介绍是在context,读这个blog之前,要先读pipelines(pipelines提出了使用 一般来说,context是用在request的处理,例如http请求的处理中,可能会开启多个goroutine,比如: http.HandleFunc(func(w http.ResponseWriter,r *http.Request){
wg := sync.WaitGroup{}
wg.Add(2)
var result0 string
go func(){
defer wg.Done()
res0,err := http.Get("http://server0/api0")
// Parse res0 to result0.
}()
var result1 string
go func(){
defer wg.Done()
res1,err := http.Get("http://server1/api1")
// Parse res1 to result1.
}()
wg.Wait()
w.Write([]byte(result0 + result1)
})
实际上这个程序是不能这么写的,如果这两个goroutine请求的时间比较长,让用户一直等着么?如果用户取消了请求,关闭了连接呢?如果用户指定了超时时间呢? 另外,考虑如何关闭一个http服务器,比如需要关闭listener后重新侦听一个新的端口: var server *http.Server
go func() {
server = &http.Server{Addr: addr,Handler: nil}
if err = server.ListenAndServe(); err != nil {
ol.E(nil,"API serve failed,err is",err)
return
}
}()
我们如何确保goroutine已经退出后,然后才返回重新开启服务器?如果只是 在context中,有一段话非常关键: A Context does not have a Cancel method for the same reason the
Done channel is receive-only: the function receiving a
cancelation signal is usually not the one that sends the signal.
In particular,when a parent operation starts goroutines for sub-
operations,those sub-operations should not be able to cancel the
parent. Instead,the WithCancel function (described below)
provides a way to cancel a new Context value.
也就是说,context没有提供Cancel方法,因为parent goroutine会调用Cancel,在所有sub goroutines中只需要读 还有一处地方,说明了Context应该放在参数中: Server frameworks that want to build on Context should provide
implementations of Context to bridge between their packages and
those that expect a Context parameter. Their client libraries
would then accept a Context from the calling code. By
establishing a common interface for request-scoped data and
cancelation,Context makes it easier for package developers to
share code for creating scalable services.
只读取chan的好处是,可以使用 使用context和WaitGroup,同步和取消服务器的例子: func HTTPAPIServe(ctx context.Context) {
http.HandleFunc("/api",func(w http.ResponseWriter,r *http.Request) {
})
ctx,cancel := context.WithCancel(ctx)
wg := &sync.WaitGroup{}
defer wg.Wait()
wg.Add(1)
var server *http.Server
go func(ctx context.Context) {
defer wg.Done()
defer cancel()
server = &http.Server{Addr: addr,Handler: nil}
_ = server.ListenAndServe()
}(ctx)
select {
case <-ctx.Done():
server.Close()
}
}
wg := sync.WaitGroup{}
defer wg.Wait()
ctx,cancel := context.WithCancel(context.Background())
wg.Add(1)
go func(ctx context.Context) {
defer wg.Done()
defer cancel()
HTTPAPIServe(ctx)
}(ctx)
wg.Add(1)
go func(ctx context.Context) {
defer wg.Done()
defer cancel()
// Other server,such as:
// UDPServer(ctx)
}(ctx)
这个程序实际上包含了几条通道:
特别是对于library,在参数中支持context,是非常重要的一个要素,这样可以收取到user要求退出或cancel的信号。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |