Go http server and global variables

I have an http server. This is written using Go. I have this code:

package main import ( "net/http" "runtime" ) var cur = 0 func handler(w http.ResponseWriter, r *http.Request) { cur = cur + 1; } func main() { runtime.GOMAXPROCS(runtime.NumCPU()) http.HandleFunc("/", handler) http.ListenAndServe(":9010", nil) } 

It is safe? Maybe I need to use mutexes?

+6
source share
2 answers

No, this is not safe, yes, you will need to lock some form. Each connection is processed in its own goroutine. See the Serve () program for more details.

A common template is to use goroutine, which checks the channel and accepts changes through the channel:

 var counterInput = make(chan int) func handler(w http.ResponseWriter, r *http.Request) { counterInput <- 1 } func counter(c <- chan int) { cur := 0 for v := range c { cur += v } } func main() { go counter(counterInput) // setup http } 

Related: Is using "net / http" global variables considered good practice in golang? .

+4
source

If I don’t notice something, in this case, instead of using a lock (or channel), you can use the found tools in the sync/atomic package (although you need to make your type int32 or int64 )

However, the documentation itself recommends you otherwise.

These functions require great care so that they can be used correctly. With the exception of special low-level applications, synchronization is best done with channels or means of the synchronization package. Exchange memory by exchanging data; Do not exchange data using memory exchange.

+1
source

Source: https://habr.com/ru/post/954280/


All Articles