SetCurrentDirectory in a multi-threaded application

I understand that SetCurrentDirectory should not be used in a multi-threaded application, since the current directory is shared between all threads of the process.

What is the best approach to setting up a directory with this in mind. In most cases, you can avoid installing the directory by including the full path when opening files instead of navigating to them first using SetCurrentDirectory, but is this the only solution?

+4
source share
3 answers

I have encountered this problem before.

Any object that needs the concept of the current directory to support relative paths or searches (for example, a build tool) has a member property that it maintains with its "current" path, and then creates the full path to open / create / search.

The initial value for CurrentPath can be obtained once during the application loading phase, for example. main (), WinMain (), DllInit (), etc. through GetCurrentDirectory and stored on the global network. After that, the Win32 version is ignored.

The OPENFILENAME structure has an initial directory element, so there is no need to use the current Win32 directory in the file open / save dialog box.

+7
source

Each process has one current directory, so if you want a different current directory to be used in each thread of your process, I think you should specify the full path in each.

+1
source

Advice on using full paths in shared and local paths is only an exception (and very carefully) when necessary. That is, the OpenFile Dialog may or may not change the current directory (depending on the attributes), etc. Using file names or local paths is a potential cause of problems.

In my experience, full paths do not slow down file access significantly. I wrote an application that every minute opens thousands of files and writes sorted data to other thousands of files - they all use full paths and everything on a network drive connected to the window. The bottleneck was closing files. Do not open them.

+1
source

All Articles