dongxie2756 2019-06-27 22:35
浏览 42
已采纳

完成2个goroutine后删除文件

I have a simple goroutine, that calls a local binary (rsync) that points to a temporary text file containing list of files to operate on, with a destination directory. At the end of the routine, I remove the tempfile. No issues here.

But in certain cases the same temp file needs to be used, when there are two destinations that are called in a range loop, e.g.:

destDirs := []string{"dir1/", "dir2/"}
for _, dest := range destDirs {
  go launchRoutine(tempfile.Name(), dest)
}

Since launchRoutine can take a while to run, and since this is a web app, waiting until the routine finishes is not an option.

Question is, where it be best to place the os.Remove(tempfile) code?

Option 1 - send launchRoutine a slice instead of a string, and loop over it in launchRoutine, and remove the file then.

Option 2 - send a bool to launchRoutine to remove the file when the range loop is at last iteration.

Option 3 - No idea? Any idiomatic ways I haven't thought of?

Solution I went with, @RJS's comments seem to validate the solution:

destDirs := []string{"dir1/", "dir2/"}
for _, dest := range destDirs {
  go launchRoutine(tempfile.Name(), dest)
}
os.Remove(tempfile.Name())

Thanks!

  • 写回答

1条回答 默认 最新

  • dpd2349 2019-06-28 01:29
    关注

    Provided I haven't misunderstood your explanation:

    • option 1, from what you've said, you'll probably want to keep the loop and maintain a coroutine for each /dest.
    • option 2, don't do that. If you're trying to share information between a fork and main/other fork you'll want to use a (sync.)waitgroup or better yet, (sync.)condition. If you leave a for exp {} in a coroutine waiting for some shared resource to change, this will eat cpu and cause a whole lot of slowdown. Even if you use a sleep in there, it trades off wasted cpu for wasted runtime and lack of coordination. Sync.condition wait() use will actually suspend the routine--allowing other routines to run in its stead, and waitgroup is a perfectly reasonable option as well.

    Maybe I'm misunderstanding, but hopefully I was of some help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据