dtz55359 2017-10-11 13:05
浏览 72
已采纳

golang同步/原子包?

I write a piece of code to record the num of request.

package main

import (
    "log"
    "net/http"
    "runtime"
    "sync/atomic"
)

var count int32 = 0

func test(w http.ResponseWriter, r *http.Request) {
    count = atomic.LoadInt32(&count)
    atomic.AddInt32(&count, 1)
    log.Println("count:", count)
}
func main() {
    runtime.GOMAXPROCS(runtime.NumCPU() - 1)
    http.HandleFunc("/", test)
    http.ListenAndServe(":8080", nil)
}

I have considered the condition of concurrency, so I use the atomic pacakge. I test the code via the apache ab tool

ab -c 400 -n 1000 http://localhost:8080/

the result is correct: result However, someone said he got the 1004 or other number on his computer, I have tested many times of the code, but the result is correct on my computer, is there wrong with my way? I am new to go, Thanks in advance.

  • 写回答

1条回答 默认 最新

  • drmlxgmqn18198265 2017-10-11 13:42
    关注

    You are using the sync/atomic package incorrectly. If you have an atomic variable, ALL reading and writing must be done using the atomic functions.

    Here is your code fixed so that the count variable is not written to or read from non-atomically:

    package main
    
    import (
        "log"
        "net/http"
        "runtime"
        "sync/atomic"
    )
    
    var count int32
    
    func test(w http.ResponseWriter, r *http.Request) {
        currentCount := atomic.LoadInt32(&count)
        atomic.AddInt32(&count, 1)
        log.Println("count:", currentCount)
    }
    func main() {
        runtime.GOMAXPROCS(runtime.NumCPU() - 1)
        http.HandleFunc("/", test)
        http.ListenAndServe(":8080", nil)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口