Reputation: 65
I am trying to change directories in a go routine to directory x. I now want to use a different go routine that changes the directory to directory y. Will the execution of my first go routine be affected by this change to the current working directory in the second go routine? The purpose of wanting to do this is to introduce parallelism while doing similar tasks. If it does end up changing the CWD, what should be an alternative approach (forking...)?
Upvotes: 3
Views: 2492
Reputation: 4290
@Evan has identified a fundamental flaw in attempting to use the 'change working directory' (CWD) system call.
I believe that @Evan is correct, and that the CWD is a thread property on some OS's.
As @Evan pointed out, a goroutine could be resheduled (for example at a function call, channel access, or system call) onto a different thread.
The implications are, it may be impossible to change the CWD (if Chdir() could change the threads CWD) because Go's runtime chooses to reschedule the goroutine on a different thread; its CWD could change invisibly and unpredictably.
Edit: I would not expect Chdir() to do anything other than change the CWD for the process. However, the documentation for the package has no mention of 'process'.
Worse, the runtime may change how things work with releases.
Even worse, it would be very hard to debug. It may be a 'Heisenberg problem', where any attempt to debug it (for example by calling a function, which the runtime may use as a reschedule point) may actually changes the behaviour in an unpredictable way.
Keep track of absolute path names. This is explicit, clear, and would even work across goroutines without any need for synchronisation. Hence it is simpler, and easier to test and debug.
Upvotes: 1
Reputation: 4604
Like mentioned in the comments, keeping track of the current working directory in each goroutine will cause problems.
Try using filepath.Abs to capture the absolute directory and store that instead. Then each goroutine can operate on it's own directory without worrying about it being "switched" under the hood. Just be sure you're not modifying the same file accidentally by multiple goroutines.
Edit: Removing a chunk of text per @Evan's comment. Use absolute paths :p
Upvotes: 5