简体   繁体   中英

SetCurrentDirectory in multi-threaded application

I understand SetCurrentDirectory shouldn't be used in a multithreaded application since the current directory is shared between all threads in the process.

What is the best approach to setting the directory with this in mind. It can mostly be avoided setting the directory by including the full pathname when opening files instead of first navigating to them with SetCurrentDirectory, but is this the only solution?

I've encountered this problem before.

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

The initial value for CurrentPath can be retrieved once during the application's load phase, eg main(), WinMain(), DllInit(), etc. via GetCurrentDirectory and stored in a global. After that the Win32 version is ignored.

The OPENFILENAME structure has an initial directory member, so file open/save dialogs don't have to use the Win32 current directory.

每个进程都有一个当前目录,因此如果您希望进程中的每个线程使用不同的当前目录,我认为您应该在每个目录中指定完整路径。

A advice to use full paths in general and local paths only as a exception (and very carefully), when needed. Ie the OpenFile Dialog may or may not change the current directory (depending on attributes) etc. Using filenames or local paths is a potential cause of trouble.

By my experience full paths do not slow down file access significantly. I wrote a app that opens thousands of files every minute and writes sorted data to other thousands of files - all using full paths and all on a windows mounted network drive. The bottleneck there was closing the files. Not opening them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM