c++ - 如何以线程安全的方式更改目录?

标签 c++ multithreading boost thread-safety chdir

我想产生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/

相关文章:

c++ - 在 C++ 中获取 Windows 文本?

c++ - 使用头文件/源文件时访问类变量时出现问题

c++ - 我们如何调试在 C++ 应用程序中使用的 matlab 制作的 DLL?

java - 进程和线程的区别

c++ - 拥有字符串映射如何将其与给定字符串进行比较

c++ - 将utf8编码的字符串转换为本地8位编码的字符串,并用空格替换不可转换的字符

c++ - 自定义开关功能中的大量神秘错误

c++ - 由于递归删除,智能指针炸毁堆栈

python - 关于 python 中多线程方法的体系结构问题

C++新线程休眠主线程