Python pytables因线程而崩溃
下面的代码显示了pytables和线程之间的交互中的问题。我正在创建一个HDF文件并用100个并发线程读取它:Python pytables因线程而崩溃,python,multithreading,hdf5,pytables,Python,Multithreading,Hdf5,Pytables,下面的代码显示了pytables和线程之间的交互中的问题。我正在创建一个HDF文件并用100个并发线程读取它: import threading import pandas as pd from pandas.io.pytables import HDFStore, get_store filename='test.hdf' with get_store(filename,mode='w') as store: store['x'] = pd.DataFrame({'y': rang
import threading
import pandas as pd
from pandas.io.pytables import HDFStore, get_store
filename='test.hdf'
with get_store(filename,mode='w') as store:
store['x'] = pd.DataFrame({'y': range(10000)})
def process(i,filename):
# print 'start', i
with get_store(filename,mode='r') as store:
df = store['x']
# print 'end', i
return df['y'].max
threads = []
for i in range(100):
t = threading.Thread(target=process, args = (i,filename,))
t.daemon = True
t.start()
threads.append(t)
for t in threads:
t.join()
程序通常执行得很干净。但我偶尔会遇到这样的例外情况:
Exception in thread Thread-27:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "crash.py", line 13, in process
with get_store(filename,mode='r') as store:
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 259, in get_store
store = HDFStore(path, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 398, in __init__
self.open(mode=mode, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 528, in open
self._handle = tables.openFile(self._path, self._mode, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tables/_past.py", line 35, in oldfunc
return obj(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tables/file.py", line 298, in open_file
for filehandle in _open_files.get_handlers_by_name(filename):
RuntimeError: Set changed size during iteration
或
在减少代码时,我得到了非常不同的错误消息,其中一些消息表示内存损坏
以下是我的图书馆版本:
>>> pd.__version__
'0.13.1'
>>> tables.__version__
'3.1.0'
我已经在写文件时遇到了一个线程错误,我通过使用选项--enable threadsafe--with pthread重新编译hdf5解决了这个问题
有人能重现这个问题吗?如何解决它?PyTables不是完全线程安全的。改用多进程池。Anthony已经指出hdf5(PyTables基本上是HDF5C库的包装器)不是线程安全的。如果要从web应用程序访问hdf5文件,基本上有两个选项:
我目前还在努力使用hdf5作为web应用程序的数据库后端。我认为上述第二种方法提供了一个不错的解决方案。但hdf5仍然不是一个数据库系统。如果您想要一个具有Python接口的真正的阵列数据库服务器,请查看。不过,它的重量远不如基于hdf5的解决方案轻。有一点尚未提及,请使用以下方法重新编译hdf5,使其成为线程安全的:
--enable-threadsafe --with-pthread=DIR
我在使用HDF5的keras代码中发现了一些难以发现的错误,这就是解决问题的方法。你能详细说明一下吗?我对多重处理几乎一无所知。我的代码是在web服务器(apache/mod_wsgi)上运行的,这就是为什么我需要我的代码是线程安全的。谢谢你的建议。正如我所说,我已经用--thread safe选项重新编译了hdf5库,所以我认为hdf5应该是线程安全的。我注意到,即使我不访问文件,但只使用
numpy
来管理阵列,我也会遇到问题。。。可能是线程问题。我的实际解决方案是将threads=1
放在mod\u wsgi
的配置中:这似乎解决了所有问题。我想这意味着我将使用多进程但使用单线程。我也会看看scidb
。。。
--enable-threadsafe --with-pthread=DIR