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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line