drpmazn9021 2016-04-28 00:20
浏览 43
已采纳

在Go中并发使用变量始终可以吗?

I'm writing a small webserver program, and it does a lot of JSON decoding from POST requests coming in.

Initially I thought that instead of initializing a new json.Decoder every time a request comes in, I have it as a global variable that gets called on every time and decodes concurrently with goroutines.

As a newcomer to Go, is this okay? Are there times when I shouldn't be doing this and classes will freak out due to not being thread safe (I guess "goroutine" safe would be better)?

  • 写回答

2条回答 默认 最新

  • dtpd58676 2016-04-28 06:18
    关注

    In Go, json.NewDecoder takes an io.Reader as an input parameter and returns a *json.Decoder. Hence it is not possible to reuse the same Decoder since we have a different http.Request.Body (which implements io.Reader) for each POST request.

    And as mentioned by Paul Hankin, you can't use go objects concurrently unless they're documented to be safe to use concurrently.

    Examples :

    1. http.Client & http.Transport

      Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used.

    Source

    1. Maps

      After long discussion it was decided that the typical use of maps did not require safe access from multiple goroutines.

    Source

    If you asked about reusing JSON decoder to avoid the duplication of code you could look at frameworks like Tigertonic and Go-Json-Rest.

    On a side note you could look at ffjson to speed up JSON Decoding.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了