DataLoader 多線程讀取數據
使用DataLoader讀取數據時,爲了加快效率,所以使用了多個線程,即num_workers不爲0,在windows下報了錯誤。
DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)
https://github.com/pytorch/pytorch/pull/5585 這裏是官方說明了一些原因,應該是windows下的一些線程文件讀寫的問題
在Windows上,FileMapping對象應必須在所有相關進程都關閉後,才能釋放。
啓用多線程處理時,子進程將創建FileMapping,然後主進程將打開它。 之後當子進程將嘗試釋放它的時候,因爲父進程還在引用,所以它的引用計數不爲零,無法釋放。 但是當前代碼沒有提供在可能的情況下再次關閉它的機會。這個版本官方說num_workers=1是可以用的,更多的線程還在解決,不過現在即便是用2個子進程也已經可以了。
解決方法有二(各自均親測有效)
- num_workers=0,也就是單線程操作
- 在使用DataLoader讀取之前加上 if name == '__main__' : 就可以了。
報錯信息如下:
in _Popen
is not going to be frozen to produce an executable.''')
return _default_context.get_context().Process._Popen(process_obj)
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
File "multiprocessing\context.py", line 322, in _Popen
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
return Popen(process_obj)
in the main module:
if __name__ == '__main__':
File "multiprocessing\popen_spawn_win32.py", line 89, in __init__
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable. reduction.dump(process_obj, to_child)