首页 > 解决方案 > 将python中的多个线程分配给命令行工具

问题描述

首先,我对这个话题的了解非常有限,但我很好奇这是否可能。我有许多必须在 Linux 中使用命令行工具处理的大型数据样本。我可以使用大约 14 个线程,但该工具并未使用所有线程。我想知道是否可以将 14 个线程分成两个“组”,然后以并行方式在不同的数据样本上运行相同的工具,每个都有 7 个线程。我阅读了有关多处理的信息,但据我了解,我只能为该工具使用 1 个线程(对不起,如果我在这里错了,这是我所理解的)。

所以我的问题是:

  1. 可以制作多组线程
  2. 让我的命令行工具使用这些组并行运行

例如:

def function_to_run_tool(data_sample):
    cmd = 'command to run command line tool one one of the samples'

function_to_run_tool(sample) # This function runs in parallel on 7 threads per sample

基本上,拥有超过 1 个线程的某种工作人员会很酷。

标签: pythonlinuxpython-multithreading

解决方案


您不能在更多线程上运行单个程序,除非该程序将自身分离为线程。这就像您希望您的处理器运行您制作的程序而无需编写更多线程一样:它不能。解决方案是将您的数据拆分为 14 个部分并为每个部分设置一个线程,或者如果该工具是您制作的,那么您可以更改它,以便它为每个数据集使用更多线程.

要实现该行为,您可以使用 threading 模块:

import threading

sample1 = your_first_sample
sample2 = your_second_sample

def function_to_run_tool(data_sample):
    cmd = 'command to run command line tool one one of the samples'

thread1 = threading.Thread(function_to_run_tool, [sample1, ])
thread2 = threading.Thread(function_to_run_tool, [sample2, ])
thread1.start()
thread2.start()
thread1.join()
thread2.join()

样本必须以数组的形式传递给线程构造函数,因为它将整个数组作为给定函数的 *args


推荐阅读