os.makedirs(path, exist_ok=True) 会受到竞争条件影响吗?

0 投票
1 回答
34 浏览
提问于 2025-04-14 15:46

假设有两个不同的进程同时调用 os.makedirs(path, exist_ok=True)。会不会因为竞争条件(race condition)而导致其中一个进程抛出一个错误呢?

我担心这个调用在内部可能会像这样处理:

if not dir_exists(d):
    try_make_dir_and_raise_if_exists(d)

我仔细阅读了文档,但没有看到明确说明它是安全的,能够避免竞争条件。

这个网站上其他一些回答说这个调用是安全的,但没有提供任何引用。

1 个回答

3

查看一下这个源代码

try:
    makedirs(head, exist_ok=exist_ok)
except FileExistsError:
    # Defeats race condition when another thread created the path
    pass

所以如果其他人创建了相同的路径,也不会出现异常。

撰写回答