解决与 goroutines 的冲突?
Resolving conflicts with goroutines?
我有一个非常小的疑问
假设有三个func A,B,C
A 和 B 都在调用 C
我是 运行 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()
以后运行这两个go routines
会不会有冲突或者运行时错误
多个 goroutines 是否安全 运行 并发取决于它们是否共享数据而不同步。在此示例中,abc
和 xyz
使用 fmt.Println
打印到 stdout
,并调用相同的例程 call
,打印到 stdout
使用 fmt.Println
。由于 fmt.Println
doesn't use synchronization when printing to stdout
,答案是否定的,此程序不安全。
我有一个非常小的疑问 假设有三个func A,B,C A 和 B 都在调用 C 我是 运行 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()
以后运行这两个go routines
会不会有冲突或者运行时错误多个 goroutines 是否安全 运行 并发取决于它们是否共享数据而不同步。在此示例中,abc
和 xyz
使用 fmt.Println
打印到 stdout
,并调用相同的例程 call
,打印到 stdout
使用 fmt.Println
。由于 fmt.Println
doesn't use synchronization when printing to stdout
,答案是否定的,此程序不安全。