gpt4 book ai didi

python - 从导入的模块线程初始化类变量在 Python 中是安全的吗?

转载 作者:行者123 更新时间:2023-12-05 04:36:34 26 4
gpt4 key购买 nike

我知道类变量初始化发生在导入时。如果是这样,在下面的代码中,类 A 的类变量初始化是否会导致竞争条件?

a.py:

class A:
# Static code here...
pass

b.py:

class B:
def func(self):
from a import A

c.py:

import threading
from b import B

b1 = B()
b2 = B()

t1 = threading.Thread(target=b1.func)
t2 = threading.Thread(target=b2.func)

t1.start()
t2.start()

t1.join()
t2.join()

航站楼:

$ python c.py

最佳答案

在 importlib 的 CPython 实现中,C 端有一个线程锁,但为了确定,我运行了以下脚本:

导入文件:

import time
print('importing, in imported file')
time.sleep(2) # drop the GIL
print('finished importing, in imported file')

导入文件:

import threading

def import_other_file():
print('going to import')
import ex12
print('finished importing')

t1 = threading.Thread(target=import_other_file)
t2 = threading.Thread(target=import_other_file)

t1.start()
t2.start()

t1.join()
t2.join()

输出:

going to import
going to import
importing, in imported file
finished importing, in imported file
finished importing
finished importing

does the class variable initialization of class A result in race conditions?

所以NO,不会因为C端的锁而出现竞争条件。

关于python - 从导入的模块线程初始化类变量在 Python 中是安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70803361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com