Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
multiprocessing.pool中的Python线程池无法使用所有CPU_Python_Multithreading - Fatal编程技术网

multiprocessing.pool中的Python线程池无法使用所有CPU

multiprocessing.pool中的Python线程池无法使用所有CPU,python,multithreading,Python,Multithreading,我在Python中有一些字符串处理工作。我希望加快这项工作 通过使用线程池。字符串处理作业对每个作业都没有依赖关系 其他的。结果将存储到mongodb数据库中 我编写的代码如下: thread_pool_size = multiprocessing.cpu_count() pool = ThreadPool(thread_pool_size) for single_string in string_list: pool.apply_async(_process, [single_stri

我在Python中有一些字符串处理工作。我希望加快这项工作 通过使用线程池。字符串处理作业对每个作业都没有依赖关系 其他的。结果将存储到mongodb数据库中

我编写的代码如下:

thread_pool_size = multiprocessing.cpu_count()
pool = ThreadPool(thread_pool_size)
for single_string in string_list:
    pool.apply_async(_process, [single_string ])
pool.close()
pool.join()

def _process(s):
    # Do staff, pure python string manipulation.
    # Save the output to a database (pyMongo).
我尝试在具有8个CPU内核的Linux机器上运行代码。结果证明 当我 运行作业几分钟


我使用线程池的方法正确吗?有更好的方法吗?

也许
\u进程
没有CPU限制;如果您正在写入数据库,文件系统或网络可能会减慢速度。如果使进程真正受CPU约束,您可以看到CPU使用率是否会上升,例如:

def _process(s):
    for i in xrange(100000000):
        j = i * i

您可以使用多个进程而不是多个线程进行检查。这是两种选择的一个很好的比较。其中一条评论指出,Python在处理多个线程时不能使用多个CPU(由于全局解释器锁)。因此,您不应该使用线程池,而应该使用进程池来充分利用您的机器。

您使用的是内置的
多处理模块还是单独的模块?Python 2.7的内置模块。ThanksI删除MongoDB标记有两个原因:第一,显示的代码与此无关。第二,问题是针对Pythons的多处理能力。请不要将整个堆栈添加到标签中。我使用这个函数,发现CPU使用率现在上升到300%左右,这要好得多。但我有可能增加更多吗?8核CPU的理论极限是800%,对吗?我曾经认为ThreadPool使用进程池在Python中实现,因为它在多处理包中。但是在我用进程池替换线程池之后,速度提高了很多。我会做更多的研究,如果有新的发现,我可能会更新这个问题。非常感谢。