【发布时间】:2018-04-26 18:30:57
【问题描述】:
我有两个 goroutine go doProcess_A() 和 go doProcess_B()。两者都可以调用saveData(),一个非goroutine方法。
我应该使用 go saveData() 而不是 saveData() 吗? 哪个安全?
var waitGroup sync.WaitGroup
func main() {
for i:=0; i<4; i++{
waitGroup.Add(2)
go doProcess_A(i)
go doProcess_B(i)
}
waitGroup.Wait()
}
func doProcess_A(i int) {
// do process
// the result will be stored in data variable
data := "processed data-A as string"
uniqueFileName := "file_A_"+strconv.Itoa(i)+".txt"
saveData(uniqueFileName, data)
waitGroup.Done()
}
func doProcess_B(i int) {
// do some process
// the result will be stored in data variable
data := "processed data-B as string"
uniqueFileName := "file_B_"+strconv.Itoa(i)+".txt"
saveData(uniqueFileName, data)
waitGroup.Done()
}
// write text file
func saveData(fileName ,dataStr string) {
// file name will be unique.
// there is no chance to be same file name
err := ioutil.WriteFile("out/"+fileName, []byte(dataStr), 0644)
if err != nil {
panic(err)
}
}
这里,一个goroutine是否在其他goroutine正在做的时候等待磁盘文件操作? 或者,是否有两个 goroutine 制作了自己的 saveData() 副本?
【问题讨论】:
-
我不确定您所说的“SaveData() 的副本”是什么意思,但
saveData不使用任何共享值,因此并发调用它没有什么不安全的。
标签: go concurrency goroutine