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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题