完成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!

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.