多个Go协程是否会阻碍同一个函数中的变量?

huangapple go评论73阅读模式
英文:

Can multiple go routines hinder variables in a same function?

问题

我的问题可能很愚蠢,请忍耐一下。如果两个Go协程调用同一个函数,它们会共享该函数中的变量吗?在函数内部声明变量并自由使用是安全的吗?

在上面的代码中,当两个Go协程调用相同的函数时,它们会干扰彼此的变量声明吗?如果Go协程的顺序不同或其他情况,something的值会改变吗?

英文:

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?

答案1

得分: 2

它们会阻碍变量声明吗 - 不会。本质上它是一个函数..所以如果你在函数内部声明变量..就不会有任何问题,它可以正常工作。

但是,如果变量没有在函数内部声明,而是在函数范围之外声明,那么goroutine的顺序将会影响值。
例如

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) // 粗暴的方法,没有使用通道或者等待组。
}
英文:

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.
}

huangapple
  • 本文由 发表于 2022年11月25日 20:35:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/74572901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定