c++multithreadingboostthread-safetychdir

How can I change directories in a thread safe way?


I'd like to spawn 2 threads and move each one into a different working directory.

std::thread t1([](){
    boost::filesystem::current_path("/place/one");
    // operate within "place/one"
});

std::thread t2([](){
    boost::filesystem::current_path("/place/two");
    // operate within "place/two"
});

t1.join();
t2.join();

However, this will not work.

Boost documentation shows the following:

void current_path(const path& p);

Effects: Establishes the postcondition, as if by ISO/IEC 9945 chdir().

Postcondition: equivalent(p, current_path()).

Throws: As specified in Error reporting.

[Note: The current path for many operating systems is a dangerous global state. It may be changed unexpectedly by a third-party or system library functions, or by another thread. -- end note]

Since current_path i.e. chdir are not thread safe, the last thread to change directories will affect the global state of the other thread.
They will both operate in the same directories.

But what is my alternative? Based on the existing code, I'm hoping to avoid rewiring thread logic on the assumption of a different current working directory. Are spawning processes my only other option?


Solution

  • As a UNIX process has a unique current directory shared by all its threads, spawning a process is indeed a requirement if you need different current_path. However, portability will suffer from it.