Skip to content

Instantly share code, notes, and snippets.

@tanapoln
Last active September 13, 2020 09:36
Show Gist options
  • Save tanapoln/04df4c2134883c687d0f87067cf25f19 to your computer and use it in GitHub Desktop.
Save tanapoln/04df4c2134883c687d0f87067cf25f19 to your computer and use it in GitHub Desktop.
Concurrency Problem - code sample
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
quota := 1000
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"remain": quota,
})
})
r.GET("/use", func(c *gin.Context) {
if quota <= 0 {
c.JSON(400, gin.H{
"status": "OUT OF QUOTA",
})
} else {
quota--
c.JSON(200, gin.H{
"status": "OK",
})
}
})
r.Run()
}
package main
import (
"sync/atomic"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
var quota int32 = 1000
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"remain": quota,
})
})
r.GET("/use", func(c *gin.Context) {
if atomic.LoadInt32(&quota) <= 0 {
c.JSON(400, gin.H{
"status": "OUT OF QUOTA",
})
} else {
atomic.AddInt32(&quota, -1)
c.JSON(200, gin.H{
"status": "OK",
})
}
})
r.Run()
}
package main
import (
"sync"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
var quota int32 = 1000
var lock sync.Mutex
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"remain": quota,
})
})
r.GET("/use", func(c *gin.Context) {
lock.Lock()
defer lock.Unlock()
if quota <= 0 {
c.JSON(400, gin.H{
"status": "OUT OF QUOTA",
})
} else {
quota--
c.JSON(200, gin.H{
"status": "OK",
})
}
})
r.Run()
}
#download go dependency
go get -u github.com/gin-gonic/gin
#start server
go run demo-1.go
#run test - 1 concurrent
ab -n 1000 -c 1 http://localhost:8080/use
#run test - 10 concurrent
ab -n 1000 -c 10 http://localhost:8080/use
#check remain quota
curl http://localhost:8080
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment