解决goroutine冲突的方法?

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

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是否可以安全地并发运行取决于它们是否在没有同步的情况下共享数据。在这个例子中,abcxyz都使用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.

huangapple
  • 本文由 发表于 2016年10月29日 17:32:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/40317747.html
匿名

发表评论

匿名网友

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

确定