我如何写一个健壮的多线程映射函数?



我可以成功地应用这个函数来并行化跨列表的函数:

def multiprocessing_run_func_with_list(func_now, list_now,threadingcount=8): 
from multiprocessing import Pool, TimeoutError
with Pool(processes=threadingcount) as pool:
results = pool.map(func_now, list_now)

return results

然而,当我切换到线程,木星笔记本只是死机运行以下。(以前运行得很好……不知道为什么它现在不能正常运行…)

def multithreading_run_func_with_list(func_now, list_now,threadingcount=8): 
from multiprocessing.pool import ThreadPool
if threadingcount is not None:
threads = ThreadPool(threadingcount) # Initialize the desired number of threads
else:
threads = ThreadPool(len(list_now)) # Initialize the desired number of threads
#     results = threads.map(func_now, list_now)
results = threads.starmap(func_now, [(j,) for j in list_now])

return results
是否有错误/更好的方法来调用这样的多线程?

Python限制多线程以避免内存冲突(它使用GIL来避免内存冲突)。我建议你只使用多处理和批处理来利用你所有的内核,而不是尝试多线程——多线程和python只是在语言的最基本层面上不能混合。

祝你好运!

最新更新