英文:
Resolving conflicts with goroutines?
问题
我有一个非常小的疑问。假设有三个函数A、B、C。C被A和B同时调用。我在不同的线程上运行A和B,当它们在内部调用C时,是否会导致冲突?
为了参考,我添加了这段代码:
package main
import (
"fmt"
)
func xyz() {
for true {
fmt.Println("Inside xyz")
call("xyz")
}
}
func abc() {
for true {
fmt.Println("Inside abc")
call("abc")
}
}
func call(s string) {
fmt.Println("call from " + s)
}
func main() {
go xyz()
go abc()
var input string
fmt.Scanln(&input)
}
这里A = xyz(),B = abc(),C = call()。
在运行这两个goroutine时,是否会有任何冲突或运行时错误?
英文:
I have a really minor doubt
Suppose there are three func A,B,C
C is being called from both A and B
I am running A and B on different threads , will it result in conflict any time in feature when it calls C within it
for reference i am adding this code
package main
import (
"fmt"
)
func xyz() {
for true {
fmt.Println("Inside xyz")
call("xyz")
}
}
func abc() {
for true {
fmt.Println("Inside abc")
call("abc")
}
}
func call(s string) {
fmt.Println("call from " + s)
}
func main() {
go xyz()
go abc()
var input string
fmt.Scanln(&input)
}
Here A = xyz(), B = abc(), C = call()
will there be any conflict or any runtime error in future while running these two go routines
答案1
得分: 1
多个goroutine是否可以安全地并发运行取决于它们是否在没有同步的情况下共享数据。在这个例子中,abc
和xyz
都使用fmt.Println
打印到stdout
,并调用相同的例程call
,该例程使用fmt.Println
打印到stdout
。由于fmt.Println
在打印到stdout
时不使用同步,所以答案是否定的,这个程序是不安全的。
英文:
Whether multiple goroutines are safe to run concurrently or not comes down to whether they share data without synchronization. In this example, both abc
and xyz
print to stdout
using fmt.Println
, and call the same routine, call
, which prints to stdout
using fmt.Println
. Since fmt.Println
doesn't use synchronization when printing to stdout
, the answer is no, this program is not safe.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论