Tuesday, December 7, 2010

Relative paths and multithreaded applications

Tip   - Using relative paths in multi-threaded applications can create unpredictable results
Details -
The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. Using relative path names in multithreaded applications or shared library code can cause unpredictable results, when some code portion sets the current directory.  

This limitation also applies to the GetCurrentDirectory and GetFullPathName functions. Similarly, the common file dialog changes the current directory when we navigate  the file system using the file dialog; unless otherwise we specify OFN_NO­CHANGE­DIR flag. Finally, the parent application which created the common file dialog will end up with a current directory that the developer never dreamt of. So, do not assume that “current directory = application directory”. It depends on the APIs used, implicit behaviors like  in  common file dialog etc.

          LPSTR lpszDir = new TCHAR[100];
          GetCurrentDirectory( 100, lpszDir );
          CFileDialog dirChanger( TRUE );
// Do some maneuvers with myDirChanger dialog. Navigate to other folders.
          GetCurrentDirectory( 100, lpszDir );

In the above example, the two GetCurrentDirectory() calls return different paths. That means, the "." refers to entirely different locations before and after the CFileDialog usage.

To conclude:
1.    Be careful to use relative paths in multi-threaded applications.
2.    Avoid the usage of “SetCurrentDirectory” in multi-threaded applications.
3.    The path returned by “GetCurrentDirectory” may not be the path where the application is located.

Reference         -

Posted By :Praveen E

No comments:

Post a Comment