[英]Python Multithreading Pool Windows Freeze
import multiprocessing as mp
with mp.Pool(3) as pool:
res = pool.starmap(sim.cosine, ((std_matrix[i], std_matrix[j]) for i in range(nU) for j in range(nU)))
pool.close()
pool.join()
cos_matrix_uu = np.array(res).reshape(nU, nU)
在上面的代码中nU = 6040
,因此总共I循环36.481.600 (6040 * 6040)
。
我在二维数组std_matrix
中具有值( std_matrix
)。
foreach std_matrix
每对行我计算余弦相似度:
def cosine(a, b):
"""Calculates the Cosine Similarity.
:param a: array of ratings
:param b: array of ratings
:return: Cosine Similarity
"""
divisor = (np.sqrt(np.dot(a, a)) * np.sqrt(np.dot(b, b)))
if divisor == 0:
return 0
return np.divide(np.dot(a, b), divisor)
当我在不使用多线程的情况下运行此代码时,它将执行,但在使用多线程的情况下,我的电脑将冻结。 即使我使用3个线程。
我的GPU是GTX850M。 我可能做错了什么?
您的任务是CPU密集型任务,而不是IO密集型任务。 由于python的GIL,python的多线程无法分发到多核。 因此,此时只有一个线程可以运行。 它不适用于此任务类型。 只需使用多进程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.