我想产生2个线程,并将每个线程移到不同的工作目录中。
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();
但是,这将不起作用。
Boost文档显示以下内容:
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]
由于
current_path
(即chdir
)不是线程安全的,因此更改目录的最后一个线程将影响另一个线程的全局状态。它们都将在同一目录中运行。
但是我有什么选择呢?基于现有代码,我希望避免在假设当前工作目录不同的情况下重新布线线程逻辑。产卵过程是我唯一的选择吗?
最佳答案
由于UNIX进程的所有线程共享一个唯一的当前目录,因此,如果需要不同的current_path,则确实需要生成一个进程。
但是,可移植性将受到影响。
关于c++ - 如何以线程安全的方式更改目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59573987/