将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

基本上,拥有一个以上线程的某种工人是很酷的。

您不能在多个线程上运行单个程序,除非该程序将自身分离为多个线程。这就像你希望你的处理器在没有编码的情况下运行一个你制作的程序到更多的线程中:它做不到。解决方案是将数据拆分为14个部分,每个部分有一个线程,或者如果该工具是由您制作的,则可以对其进行更改,以便为每个数据集使用更多线程。

为了实现这种行为,您可以使用线程模块:

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

最新更新