xarray读取nc文件HDF5报错如下:
HDF5-DIAG: Error detected in HDF5 (1.12.2) thread 19:
#000: H5A.c line 528 in H5Aopen_by_name(): can't open attribute
major: Attribute
minor: Can't open object
#001: H5VLcallback.c line 1091 in H5VL_attr_open(): attribute open failed
major: Virtual Object Layer
minor: Can't open object
#002: H5VLcallback.c line 1058 in H5VL__attr_open(): attribute open failed
major: Virtual Object Layer
minor: Can't open object
#003: H5VLnative_attr.c line 130 in H5VL__native_attr_open(): can't open attribute
major: Attribute
minor: Can't open object
#004: H5Aint.c line 545 in H5A__open_by_name(): unable to load attribute info from object header
major: Attribute
minor: Unable to initialize object
#005: H5Oattribute.c line 494 in H5O__attr_open_by_name(): can't locate attribute: '_QuantizeGranularBitRoundNumberOfSignificantDigits'
major: Attribute
minor: Object not found
解决方案:
在使用多线程处理HDF5文件(如使用xarray打开的NetCDF文件)时,可能会遇到HDF5库的线程安全问题。HDF5库并不是线程安全的,因此在多个线程中同时访问同一个文件时会导致错误。
为了解决这个问题,我们可以使用以下几种方法:
方法一:使用多进程而不是多线程
使用concurrent.futures.ProcessPoolExecutor替代ThreadPoolExecutor。进程之间是完全隔离的,可以避免HDF5的线程安全问题。
from concurrent.futures import ProcessPoolExecutor
class abc(object):
def __init__(self, outdir, hourly):
self.outdir=outdir
self.hourly=hourly
def process_file(self, dt, h1, h2, save_path):
# somecodehere
def run(self):
with ProcessPoolExecutor() as executor:
for dt in self.daterange:
save_path = f"self.outdir/{dt}"
os.makedirs(save_path, exist_ok=True)
for h1, h2 in zip(self.hourly[:-1], self.hourly[1:]):
executor.submit(self.process_file, dt, h1, h2, save_path)
方法二:确保每个线程独占文件
如果仍想使用多线程,可以确保每个线程在处理文件时独占文件。可以使用threading.Lock来实现这一点,但这会影响性能,因此推荐使用多进程。
方法三:单线程处理
如果数据量不大,也可以选择简单地使用单线程处理,虽然这会降低处理速度,但可以避免任何并发问题。
941

被折叠的 条评论
为什么被折叠?



