如何在python中使用多线程并行化for循环

如何在python中使用多线程并行化for循环,python,parallel-processing,Python,Parallel Processing,我不熟悉python。我想为以下伪代码并行化外部for循环: for(i=1 to N){ // N and n will be taken as input for the shell script. min=some garbage value for(j=1 to n){ val= './a.out' // call the executable a.out and take the output in val if(val<min)

我不熟悉python。我想为以下伪代码并行化外部for循环:

for(i=1 to N){  // N and n will be taken as input for the shell script. 
   min=some garbage value
   for(j=1 to n){
       val= './a.out' // call the executable a.out and take the output in val
       if(val<min)    // a.out is a random number generator script
           min=val; 
   }
   arr[k++]=min;
}
// Then I want to calculate the sum of the elements of the array 'arr'.
for(i=1到N){//N和N将作为shell脚本的输入。
min=一些垃圾值
对于(j=1到n){
val='./a.out'//调用可执行文件a.out并在val中获取输出

if(val我回答这个问题是为了将来参考,尽管我和其他海报一样关注并行化是否是遵循这个具体示例的正确道路

要将简单for循环与线程并行化,当然可以使用。此外,在它们的基础上增加了一个更简单的语法(注意将其切换到线程后端)


免责声明:我是joblib的原始作者。

您的数字生成器程序会占用大量CPU时间吗?否则,在多个线程中运行内部循环几乎不会获得任何好处。一次计算最小值和一次更新arr需要很少的同步。您需要使用编译的随机变量吗数字生成器?Python有一个
random
模块。Python还可以使用内置的
sum
函数将数组中的所有元素相加(例如
sum([1,2,3])
将给出6的答案)。
#!/bin/bash
# set min to some garbage value

N=$1
n=$2
for (( i=1; i<=$N; i++ )); do
   min=100000000
   for (( j=1; j<=$n; j++ )); do
       val=$(/path/to/a.out)
       val2=`echo $val | bc`    // is this the correct syntax?
       if (( $val2 < $min )); then
           min=$val2; 
       fi   
   done
   arr=("${arr[@]}" "$min")
done

# Then I want to calculate the sum of the elements of the array 'arr'.
sum=0
for (( l=0; l<${#arr[@]}; l++ )); do
  sum=$( expr $sum + ${arr[$l]} )
done

echo "Sum of \$arr = ${sum}"