欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

golang中context的作用詳解

 更新時間:2021年01月08日 14:24:10   作者:夢回故里  
這篇文章主要介紹了golang中context的作用,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

當(dāng)一個goroutine可以啟動其他goroutine,而這些goroutine可以啟動其他goroutine,依此類推,則第一個goroutine應(yīng)該能夠向所有其它goroutine發(fā)送取消信號。

上下文包的唯一目的是在goroutine之間執(zhí)行取消信號,而不管它們?nèi)绾紊伞I舷挛牡慕涌诙x為:

type Context interface {
 Deadline() (deadline time.Time, ok bool)
 Done() <- chan struct{}
 Err() error
 Value(key interface{}) interface{}
}
  • Deadline:第一個值是截止日期,此時上下文將自動觸發(fā)“取消”操作。第二個值是布爾值,true表示設(shè)置了截止日期,false表示未設(shè)置截止時間。如果沒有設(shè)置截止日期,則必須手動調(diào)用cancel函數(shù)來取消上下文。
  • Done:返回一個只讀通道(僅在取消后),鍵入struct {},當(dāng)該通道可讀時,表示父上下文已經(jīng)發(fā)起了取消請求,根據(jù)此信號,開發(fā)人員可以執(zhí)行一些清除操作,退出goroutine
  • Err:返回取消上下文的原因
  • Value:返回綁定到上下文的值,它是一個鍵值對,因此您需要傳遞一個Key來獲取相應(yīng)的值,此值是線程安全的

要創(chuàng)建上下文,必須指定父上下文。兩個內(nèi)置上下文(背景和待辦事項)用作頂級父上下文:

var (
 background = new(emptyCtx)
 todo = new(emptyCtx)
)
func Background() Context {
 return background
}
func TODO() Context {
 return todo
}

背景,主要ü在主函數(shù),初始化和測試代碼的sed,是樹結(jié)構(gòu)中,根上下文,這是不能被取消的頂層語境。TODO,當(dāng)您不知道要使用什么上下文時,可以使用它。它們本質(zhì)上都是emptyCtx類型,都是不可取消的,沒有固定的期限,也沒有為Context賦任何值:鍵入emptyCtx int

type emptyCtx int
func (_ *emptyCtx) Deadline() (deadline time.Time, ok bool) {
 return
}
func (_ *emptyCtx) Done() <- chan struct{} {
 return nil
}
func (_ *emptyCtx) Err() error {
 return nil
}
func (*emptyCtx) Value(key interface{}) interface{} {
 return nil
}

上下文包還具有幾個常用功能:func WithCancel(父上下文)(ctx上下文,取消CancelFunc)func WithDeadline(父上下文,截止時間.Time)(上下文,CancelFunc)func WithTimeout(父上下文,超時時間。持續(xù)時間)(上下文,CancelFunc)func WithValue(父上下文,鍵,val接口{})上下文

請注意,這些方法意味著可以一次繼承上下文以實現(xiàn)其他功能,例如,使用WithCancel函數(shù)傳入根上下文,它會創(chuàng)建一個子上下文,該子上下文具有取消上下文的附加功能,然后使用此方法將context(context01)作為父上下文,并將其作為第一個參數(shù)傳遞給WithDeadline函數(shù),與子context(context01)相比,獲得子context(context02),它具有一個附加功能,可在之后自動取消上下文最后期限。

WithCancel

對于通道,盡管通道也可以通知許多嵌套的goroutine退出,但通道不是線程安全的,而上下文是線程安全的。

例如:

package main
import (
 "runtime"
 "fmt"
 "time"
 "context"
)
func monitor2(ch chan bool, index int) {
 for {
  select {
  case v := <- ch:
   fmt.Printf("monitor2: %v, the received channel value is: %v, ending\n", index, v)
   return
  default:
   fmt.Printf("monitor2: %v in progress...\n", index)
   time.Sleep(2 * time.Second)
  }
 }
}
func monitor1(ch chan bool, index int) {
 for {
  go monitor2(ch, index)
  select {
  case v := <- ch:
   // this branch is only reached when the ch channel is closed, or when data is sent(either true or false)
   fmt.Printf("monitor1: %v, the received channel value is: %v, ending\n", index, v)
   return
  default:
   fmt.Printf("monitor1: %v in progress...\n", index)
   time.Sleep(2 * time.Second)
  }
 }
}
func main() {
 var stopSingal chan bool = make(chan bool, 0)
 for i := 1; i <= 5; i = i + 1 {
  go monitor1(stopSingal, i)
 }
 time.Sleep(1 * time.Second)
 // close all gourtines
 cancel()
 // waiting 10 seconds, if the screen does not display <monitorX: xxxx in progress...>, all goroutines have been shut down
 time.Sleep(10 * time.Second)
 println(runtime.NumGoroutine())
 println("main program exit!!!!")
}

執(zhí)行的結(jié)果是:

monitor1: 5 in progress...
monitor2: 5 in progress...
monitor1: 2 in progress...
monitor2: 2 in progress...
monitor2: 1 in progress...
monitor1: 1 in progress...
monitor1: 4 in progress...
monitor1: 3 in progress...
monitor2: 4 in progress...
monitor2: 3 in progress...
monitor1: 4, the received channel value is: false, ending
monitor1: 3, the received channel value is: false, ending
monitor2: 2, the received channel value is: false, ending
monitor2: 1, the received channel value is: false, ending
monitor1: 1, the received channel value is: false, ending
monitor2: 5, the received channel value is: false, ending
monitor2: 3, the received channel value is: false, ending
monitor2: 3, the received channel value is: false, ending
monitor2: 4, the received channel value is: false, ending
monitor2: 5, the received channel value is: false, ending
monitor2: 1, the received channel value is: false, ending
monitor1: 5, the received channel value is: false, ending
monitor1: 2, the received channel value is: false, ending
monitor2: 2, the received channel value is: false, ending
monitor2: 4, the received channel value is: false, ending
1
main program exit!!!!

這里使用一個通道向所有g(shù)oroutine發(fā)送結(jié)束通知,但是這里的情況相對簡單,如果在一個復(fù)雜的項目中,假設(shè)多個goroutine有某種錯誤并重復(fù)執(zhí)行,則可以重復(fù)關(guān)閉或關(guān)閉該通道通道,然后向其寫入值,從而觸發(fā)運行時恐慌。這就是為什么我們使用上下文來避免這些問題的原因,以WithCancel為例:

package main
import (
 "runtime"
 "fmt"
 "time"
 "context"
)
func monitor2(ctx context.Context, number int) {
 for {
  select {
  case v := <- ctx.Done():
   fmt.Printf("monitor: %v, the received channel value is: %v, ending\n", number,v)
   return
  default:
   fmt.Printf("monitor: %v in progress...\n", number)
   time.Sleep(2 * time.Second)
  }
 }
}
func monitor1(ctx context.Context, number int) {
 for {
  go monitor2(ctx, number)
  select {
  case v := <- ctx.Done():
   // this branch is only reached when the ch channel is closed, or when data is sent(either true or false)
   fmt.Printf("monitor: %v, the received channel value is: %v, ending\n", number, v)
   return
  default:
   fmt.Printf("monitor: %v in progress...\n", number)
   time.Sleep(2 * time.Second)
  }
 }
}
func main() {
 var ctx context.Context = nil
 var cancel context.CancelFunc = nil
 ctx, cancel = context.WithCancel(context.Background())
 for i := 1; i <= 5; i = i + 1 {
  go monitor1(ctx, i)
 }
 time.Sleep(1 * time.Second)
 // close all gourtines
 cancel()
 // waiting 10 seconds, if the screen does not display <monitor: xxxx in progress>, all goroutines have been shut down
 time.Sleep(10 * time.Second)
 println(runtime.NumGoroutine())
 println("main program exit!!!!")
}

WithTimeout和WithDeadline

WithTimeout和WithDeadline在用法和功能上基本相同,它們都表示上下文將在一定時間后自動取消,唯一的區(qū)別可以從函數(shù)的定義中看出,傳遞給WithDeadline的第二個參數(shù)是類型time.Duration類型,它是一個相對時間,表示取消超時后的時間。例:

package main
import (
 "runtime"
 "fmt"
 "time"
 "context"
)
func monitor2(ctx context.Context, index int) {
 for {
  select {
  case v := <- ctx.Done():
   fmt.Printf("monitor2: %v, the received channel value is: %v, ending\n", index, v)
   return
  default:
   fmt.Printf("monitor2: %v in progress...\n", index)
   time.Sleep(2 * time.Second)
  }
 }
}
func monitor1(ctx context.Context, index int) {
 for {
  go monitor2(ctx, index)
  select {
  case v := <- ctx.Done():
   // this branch is only reached when the ch channel is closed, or when data is sent(either true or false)
   fmt.Printf("monitor1: %v, the received channel value is: %v, ending\n", index, v)
   return
  default:
   fmt.Printf("monitor1: %v in progress...\n", index)
   time.Sleep(2 * time.Second)
  }
 }
}
func main() {
 var ctx01 context.Context = nil
 var ctx02 context.Context = nil
 var cancel context.CancelFunc = nil
 ctx01, cancel = context.WithCancel(context.Background())
 ctx02, cancel = context.WithDeadline(ctx01, time.Now().Add(1 * time.Second)) // If it's WithTimeout, just change this line to "ctx02, cancel = context.WithTimeout(ctx01, 1 * time.Second)"
 defer cancel()
 for i := 1; i <= 5; i = i + 1 {
  go monitor1(ctx02, i)
 }
 time.Sleep(5 * time.Second)
 if ctx02.Err() != nil {
  fmt.Println("the cause of cancel is: ", ctx02.Err())
 }
 println(runtime.NumGoroutine())
 println("main program exit!!!!")
}

WithValue

一些必需的元數(shù)據(jù)也可以通過上下文傳遞,該上下文將附加到上下文中以供使用。元數(shù)據(jù)作為鍵值傳遞,但請注意,鍵必須具有可比性,并且值必須是線程安全的。

package main
import (
 "runtime"
 "fmt"
 "time"
 "context"
)
func monitor(ctx context.Context, index int) {
 for {
  select {
  case <- ctx.Done():
   // this branch is only reached when the ch channel is closed, or when data is sent(either true or false)
   fmt.Printf("monitor %v, end of monitoring. \n", index)
   return
  default:
   var value interface{} = ctx.Value("Nets")
   fmt.Printf("monitor %v, is monitoring %v\n", index, value)
   time.Sleep(2 * time.Second)
  }
 }
}
func main() {
 var ctx01 context.Context = nil
 var ctx02 context.Context = nil
 var cancel context.CancelFunc = nil
 ctx01, cancel = context.WithCancel(context.Background())
 ctx02, cancel = context.WithTimeout(ctx01, 1 * time.Second)
 var ctx03 context.Context = context.WithValue(ctx02, "Nets", "Champion") // key: "Nets", value: "Champion"

 defer cancel()
 for i := 1; i <= 5; i = i + 1 {
  go monitor(ctx03, i)
 }
 time.Sleep(5 * time.Second)
 if ctx02.Err() != nil {
  fmt.Println("the cause of cancel is: ", ctx02.Err())
 }
 println(runtime.NumGoroutine())
 println("main program exit!!!!")
}

關(guān)于上下文,還有一些注意事項:不要將Context存儲在結(jié)構(gòu)類型中,而是將Context明確傳遞給需要它的每個函數(shù),并且Context應(yīng)該是第一個參數(shù)。

即使函數(shù)允許,也不要傳遞nil Context,或者如果您不確定要使用哪個Context,請傳遞context。不要將可能作為函數(shù)參數(shù)傳遞給上下文值的變量傳遞。

到此這篇關(guān)于golang中context的作用的文章就介紹到這了,更多相關(guān)golang中context的作用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • go語言中json處理方式詳解

    go語言中json處理方式詳解

    這篇文章主要介紹了go語言中json處理方式,文中通過實例代碼講解的非常詳細,對大家的學(xué)習(xí)或工作有一定的幫助,感興趣的小伙伴跟著小編一起來看看吧
    2024-05-05
  • 舉例詳解Go語言中os庫的常用函數(shù)用法

    舉例詳解Go語言中os庫的常用函數(shù)用法

    這篇文章主要介紹了Go語言中os庫的常用函數(shù)用法,os函數(shù)的使用是Go語言入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-10-10
  • 解析Golang中的GoPath和GoModule

    解析Golang中的GoPath和GoModule

    在Golang中,有兩個概念非常容易弄錯,第一個就是GoPath,第二個則是GoModule,很多初學(xué)者不清楚這兩者之間的關(guān)系,也就難以清晰地了解項目的整體結(jié)構(gòu),今天通過本文給大家介紹下Golang中的GoPath和GoModule相關(guān)知識,感興趣的朋友一起看看吧
    2022-02-02
  • Go語言入門13之runtime包案例講解

    Go語言入門13之runtime包案例講解

    這篇文章主要介紹了Go語言入門runtime包相關(guān)知識,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-05-05
  • Go語言中嵌入C語言的方法

    Go語言中嵌入C語言的方法

    這篇文章主要介紹了Go語言中嵌入C語言的方法,實例分析了Go語言中cgo工具的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-02-02
  • Golang實現(xiàn)Redis事務(wù)深入探究

    Golang實現(xiàn)Redis事務(wù)深入探究

    這篇文章主要介紹了Golang實現(xiàn)Redis事務(wù)深入探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01
  • Golang實現(xiàn)基于Redis的可靠延遲隊列

    Golang實現(xiàn)基于Redis的可靠延遲隊列

    redisson?delayqueue可以使用redis的有序集合結(jié)構(gòu)實現(xiàn)延時隊列,遺憾的是go語言社區(qū)中并無類似的庫。不過問題不大,本文將用Go語言實現(xiàn)這一功能,需要的可以參考一下
    2022-06-06
  • GO文件創(chuàng)建及讀寫操作示例詳解

    GO文件創(chuàng)建及讀寫操作示例詳解

    這篇文章主要為大家介紹了GO文件創(chuàng)建及讀寫操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪
    2022-04-04
  • Golang?WorkerPool線程池并發(fā)模式示例詳解

    Golang?WorkerPool線程池并發(fā)模式示例詳解

    這篇文章主要為大家介紹了Golang?WorkerPool線程池并發(fā)模式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • Go模板template用法詳解

    Go模板template用法詳解

    這篇文章主要介紹了Go標(biāo)準(zhǔn)庫template模板用法詳解;包括GO模板注釋,作用域,語法,函數(shù)等知識,需要的朋友可以參考下
    2022-04-04

最新評論