多线程Python应用程序可以更改CWD吗?

问题描述 投票:0回答:1

此代码中的

assert
语句会在任何 Python 3.11+ 解释器下引发错误吗?

如果没有此代码,可以使用任何

async
功能由另一个模块更改当前工作目录吗?

import os
cwd1 = os.getcwd()
# can another module change the CWD here?
cwd2 = os.getcwd()
assert cwd1 == cwd2

我需要知道

CWD
是否在所有情况下都与示例中的代码保持相同,或者是否由于竞争条件而必须检查(尽管这种情况可能很少见)。

换句话说,该代码是线程安全的吗?

python python-3.x multithreading thread-safety race-condition
1个回答
0
投票

工作目录由启动线程的进程拥有,因此线程可以更改 cwd。例如,这对我来说失败并出现断言错误:

import threading
import time
import os


def test2():
    time.sleep(2)
    os.chdir('../')


def test1():
    cwd1 = os.getcwd()
    time.sleep(3)
    cwd2 = os.getcwd()
    assert cwd1 == cwd2


t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
t1.join()
t2.join()
© www.soinside.com 2019 - 2024. All rights reserved.