溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在GOLANG中利用Context管理關(guān)聯(lián)goroutine

發(fā)布時(shí)間:2021-03-25 16:46:12 來源:億速云 閱讀:171 作者:Leah 欄目:編程語言

這篇文章給大家介紹怎么在GOLANG中利用Context管理關(guān)聯(lián)goroutine,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

wg := sync.WaitGroup{}
defer wg.Wait()

wg.Add(1)
go func() {
  defer wg.Done()

  ss := make(os.Signal, 0)
  signal.Notify(ss, syscall.SIGINT, syscall.SIGTERM)
  for s := ss {
    fmt.Println("Got signal", s)
    break
  }
}()

wg.Add(1)
go func() {
  defer wg.Done()

  svr := &http.Server{ Addr:":8080", Handler:nil, }
  fmt.Println(svr.ListenAndServe())
}

很清楚,起了兩個(gè)goroutine,然后用WaitGroup等待它們退出。如果它們之間沒有交互,不互相影響,那真的是蠻簡單的,可惜這樣是不行的,因?yàn)樾盘柕膅oroutine收到退出信號后,應(yīng)該通知server退出。暴力一點(diǎn)的是直接調(diào)用svr.Close(),但是如果有些請求還需要取消怎么辦呢?最好用Context了:

wg := sync.WaitGroup{}
defer wg.Wait()

ctx,cancel := context.WithCancel(context.Background())

wg.Add(1)
go func() {
  defer wg.Done()

  ss := make(chan os.Signal, 0)
  signal.Notify(ss, syscall.SIGINT, syscall.SIGTERM)
  select {
  case <- ctx.Done():
    return
  case s := <- ss:
    fmt.Println("Got signal", s)
    cancel() // 取消請求,通知用到ctx的所有g(shù)oroutine
    return
  }
}()

wg.Add(1)
go func() {
  defer wg.Done()
  defer cancel()

  svr := &http.Server{ Addr:":8080", Handler:nil, }

  go func(){
    select {
    case <- ctx.Done():
      svr.Close()
    }
  }

  fmt.Println(svr.ListenAndServe())
}

這個(gè)方式可以在新開goroutine時(shí)繼續(xù)使用,譬如新加一個(gè)goroutine,里面讀寫了UDPConn:

wg.Add(1)
go func() {
  defer wg.Done()
  defer cancel()

  var conn *net.UDPConn
  if conn,err = net.Dial("udp", "127.0.0.1:1935"); err != nil {
    fmt.Println("Dial UDP server failed, err is", err)
    return
  }

  fmt.Println(UDPRead(ctx, conn))
}()

UDPRead = func(ctx context.Context, conn *net.UDPConn) (err error) {
  wg := sync.WaitGroup{}
  defer wg.Wait()

  ctx, cancel := context.WithCancel(ctx)

  wg.Add(1)
  go func() {
    defer wg.Done()
    defer cancel()

    for {
      b := make([]byte, core.MTUSize)
      size, _, err := conn.ReadFromUDP(b)
      // 處理UDP包 b[:size]
    }
  }()

  select {
  case <-ctx.Done():
    conn.Close()
  }
  return
}

如果只是用到HTTP Server,可以這么寫:

func run(ctx contex.Context) {
  server := &http.Server{Addr: addr, Handler: nil}
  go func() {
    select {
    case <-ctx.Done():
      server.Close()
    }
  }()

  http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
  })

  fmt.Println(server.ListenAndServe())
}

如果需要提供一個(gè)API來讓服務(wù)器退出,可以這么寫:

func run(ctx contex.Context) {
  server := &http.Server{Addr: addr, Handler: nil}

  ctx, cancel := context.WithCancel(ctx)
  http.HandleFunc("/quit", func(w http.ResponseWriter, r *http.Request) {
    cancel() // 使用局部的ctx和cancel
  })

  go func() {
    select {
    case <-ctx.Done():
      server.Close()
    }
  }()

  fmt.Println(server.ListenAndServe())
}

使用局部的ctx和cancel,可以避免cancel傳入的ctx,只是影響當(dāng)前的ctx。

關(guān)于怎么在GOLANG中利用Context管理關(guān)聯(lián)goroutine就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI