dongyukang7006 2018-04-26 18:30
浏览 10

同时从两个不同的goroutine调用方法是否安全?

I have two goroutines go doProcess_A() and go doProcess_B(). Both can call saveData(), a non goroutine method.

should I use go saveData() instead of saveData() ? Which one is safe?

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

here, does one goroutine wait for disk file operation when other goroutine is doing? or, are two goroutine make there own copy of saveData() ?

  • 写回答

1条回答 默认 最新

  • doucan2102 2018-04-26 18:43
    关注

    Goroutines typically don't wait for anything except you explicitly tell them to or if an operation is waiting on a channel or other blocking operation. In your code there is a possibility of a race condition with unwanted results if multiple goroutines call the saveData() function with same filename. It appears that the two goroutines are writing to different files, therefore as long as the filenames are unique, the saveData operation will be safe in a goroutine. It doesn't make sense to use a go routine to call saveData(), don't unnecessarily complicate your life, just call it directly in the doProcess_X functions.

    Read more about goroutines and make sure you are using it where it is absolutely necessary. - https://gobyexample.com/goroutines

    Note: Just because you are writing a Go application doesn't mean you should litter it with goroutines. Read and understand what problem it solves so as to know the best time to use it.

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP