Home > Enterprise >  Can multiple go routines hinder variables in a same function?
Can multiple go routines hinder variables in a same function?

Time:11-26

My question might be dumb but please bear with me. If two go-routines are calling the same function, will they share variables in that function? Is it safe to declare variables inside the function and use freely?

func main() {
 go func1(1)
 go func1(2)
}

func func1(a int) {
 something := a
 // do something
}

In the above code when two go-routines are calling same function will they hinder with the variable declaration of each other? Will the value of something change if the go routines are not in order or something?

CodePudding user response:

will they hinder the variable declaration - no. essentially it's a function.. so if you're declaring the variable inside the function.. there won't be any issues and it works normally.

but if the variable is not declared inside the function but outside the scope of the function then the order of the go routines will hinder the value for example

import (
    "fmt"
    "time"
)

var something int

func test(a int) {
    something  = a
    fmt.Println("something", something)
}

func main() {
    fmt.Println("Testing Something")
    go test(20)
    go test(3)
    time.Sleep(1 * time.Second) // crude way without using channels or waitgroup.
}
  • Related